Steve Chambers Steve Chambers - 1 month ago 13
Java Question

How to catch all checked exceptions (in a single block) in Java?

EDIT: This question only relates to Java 1.6 (and below). Apologies for not making this clear in the original post.

The hierarchy here shows Java

Exception
s are divided into two types:
RuntimeException
and not a RuntimeException:

Java exceptions hierarchy

Am probably missing something but wouldn't it have been better to divide into something like
UncheckedException
and
CheckedException
instead? For example, the following statement has quite a few checked exceptions:

try {
transaction.commit();
} catch (SecurityException e) {
} catch (IllegalStateException e) {
} catch (RollbackException e) {
} catch (HeuristicMixedException e) {
} catch (HeuristicRollbackException e) {
} catch (SystemException e) {
}


Am only really interested in whether it succeeds or fails so would like to deal with the checked exceptions as a group but not the unchecked exceptions as it's not good practice to catch an unexpected error. So with this in mind, maybe I could do something like:

try {
transaction.commit();
} catch (Exception e) {
if (e instanceof RuntimeException) {
// Throw unchecked exception
throw e;
}
// Handle checked exception
// ...
}


But this seems horribly hacky. Is there a better way?

Answer

If I understood correctly, then you are almost there. Just catch RuntimeException. That will catch RuntimeException and everything under it in the hierarchy. Then a fallthrough for Exception, and you're covered:

try {
    transaction.commit();
} catch (RuntimeException e) {
    // Throw unchecked exception
    throw e;
} catch (Exception e) {
    // Handle checked exception
    // ...
}