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.
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.
}
You could just nest your try
statements:
try {
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
}
Although I worry this is what you mean when you say " (not underlaying) "?
You can try multiple try catch:
try {
} catch(MyException ex) {
try {
} catch(Exception ex) {
}
}
Surely this is what functions are for?
try {
doStuff();
} catch ( MyException e ) {
doMyExceptionStuff();
doGeneralExceptionStuff();
throw e;
} catch ( Exception e ) {
doGeneralExceptionStuff();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.