Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 914
Steve Chambers Avatar asked Feb 08 '13 11:02

Steve Chambers


People also ask

How do you catch multiple exceptions in single catch block?

Java allows you to catch multiple type exceptions in a single catch block. It was introduced in Java 7 and helps to optimize code. You can use vertical bar (|) to separate multiple exceptions in catch block.

Can I catch multiple exceptions Java?

In Java SE 7 and later, we can now catch more than one type of exception in a single catch block. Each exception type that can be handled by the catch block is separated using a vertical bar or pipe | .

How do I catch checked exceptions?

A checked exception is caught at compile time whereas a runtime or unchecked exception is, as it states, at runtime. A checked exception must be handled either by re-throwing or with a try catch block, whereas an unchecked isn't required to be handled.

Can we use catch statement for checked exceptions?

These exceptions can be handled by the try-catch block or by using throws keyword otherwise the program will give a compilation error. ClassNotFoundException, IOException, SQLException etc are the examples of the checked exceptions.


1 Answers

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
    // ...
}
like image 84
David Lavender Avatar answered Oct 29 '22 03:10

David Lavender