javaexceptiontry-catchruntimeexceptionchecked-exceptions

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


IMPORTANT: This question only relates to Java 6 (and below).

The hierarchy here shows Java Exceptions are divided into two types: RuntimeException and [not a RuntimeException]:

Java exceptions hierarchy

Would it not 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?


Solution

  • 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
        // ...
    }