Java Exception Handling: Subclass Catch Statements Before Superclass

When using multiple catch statements in Java, it's crucial to position exception subclasses before their superclasses. This is because a catch statement for a superclass will intercept exceptions of that type, including any of its subclasses, rendering the subclass catch statement unreachable if placed afterward. For example, consider the following program: /* This program contains an error. A subclass must come before its superclass in a series of catch statements. If not, unreachable code will be created and a compile-time error will result. */ class SuperSubCatch { public static void main(String args[]) { try { int a = 0; int b = 42 / a; } catch(Exception e) { System.out.println("Generic Exception catch."); } /* This catch is never reached because ArithmeticException is a subclass of Exception. */ catch(ArithmeticException e) { // ERROR – unreachable System.out.println("This is never reached."); } } } If you compile this program, you will encounter an error message indicating that the second catch statement is unreachable due to the first catch statement already handling all Exception-based errors, including ArithmeticException. To resolve this issue, simply reverse the order of the catch statements. This adjustment ensures that the subclass catch statement is evaluated first, allowing it to function correctly.

To view or add a comment, sign in

Explore content categories