Java-Common Error in Generic Exception Catch

Common Error in Generic Exception Catch

When you use multiple catch statements, it is important to remember that exception subclasses must come before any of their superclasses. This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, a subclass would never be reached if it came after its superclass. Further, in Java, unreachable code is an error.

If you try to compile following program, you will receive an error message stating that the second catch statement is unreachable because the exception has already been caught. Since ArrayIndexOutOfBoundsException is a subclass of Exception, the first catch statement will handle all Exception-based errors, including ArrayIndexOutOfBoundsException. This means that the second catch statement will never execute.



Program Source

class Javaapp {

    public static void main(String[] args) {
            int data[] = new int[3];
            data[5] = 200;
        }catch(Exception ex)
            System.out.println("Exception : "+ex.getClass().getName());
        }catch(ArrayIndexOutOfBoundsException ex)
            System.out.println("Exception : "+ex);
        System.out.println("Execution Complete");

Leave a Comment