IMPORTANT: This question only relates to Java 6 (and below).
The hierarchy here shows Java Exception
s are divided into two types: RuntimeException
and [not a RuntimeException]:
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?
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.
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 | .
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.
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.
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 // ... }
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