If there is a try-catch with mutiple catch-blocks, is there way to rethrow an exception to next (not underlaying) catch-clause?
Example:
try {
// some exception can occur here
} catch (MyException ex) {
// do something specific
// rethrow ex to next catch
} catch (Exception ex) {
// do logging stuff and other things to clean everything up
}
When a MyException
is thrown, I want to handle the specific stuff to that exception but then I want to handle exceptions in general (catch (Exception ex)
).
I don't want to use a finally-block and Java 7 Multi-catch is also no help here.
Any ideas how to handle this, I want to avoid redundant stuff in each catch-block. Is it better to catch Exception
only and then use instanceof
for my specific stuff?
Thanks.
If a catch block cannot handle the particular exception it has caught, you can rethrow the exception. The rethrow expression ( throw without assignment_expression) causes the originally thrown object to be rethrown.
Yes, we can define one try block with multiple catch blocks in Java. Every try should and must be associated with at least one catch block.
Re-throwing an exception means calling the throw statement without an exception object, inside a catch block. It can only be used inside a catch block.
As you can see that in rethrow method, catch block is catching Exception but it's not part of throws clause. Java 7 compiler analyze the complete try block to check what types of exceptions are thrown and then rethrown from the catch block.
public void doStuff()
{
try
{
// some exception can occur here
} catch (MyException ex){
// do something specific
cleanupAfterException(ex);
} catch (Exception ex) {
cleanupAfterException(ex);
}
}
private void cleanupAfterException(Exception ex)
{
//Do your thing!
}
I presume something like this would do?
You might want to try something like this:
try
{
}
catch(Exception ex)
{
if(ex instanceof MyException)
{
// Do your specific stuff.
}
// Handle your normal stuff.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With