Search code examples
javaexceptionchained

Cannot find symbol in the chained exception


In the following program when we try to get the main exception means exception which cause the first exception of the program then it gives the error something like this : cannot find symbol : e.getCause(); but after removing this statement System.out.println("Main Cause : " + e.getCause()); we successfully get first exception.

class chain_demo {
    static void demo() {
        //create an exception
        ArithmeticException e = new ArithmeticException("top Module");

        //cuase an exception
        e.initCause(new NullPointerException("Cause"));

        //throw exception
        throw e;
    }

    public static void main(String args[]) {
        try {
            demo();
        }
        catch(ArithmeticException e) {
            //display top_level exception
            System.out.println("Cautch : " + e);
        }

        //display cause exception
        //getting error here
        System.out.println("Main Cause : " + e.getCause());
    }
}

So, How can i get the cause exception.


Solution

  • Variable e scope is limited only till the catch block Move

    System.out.println("Main Cause : " + e.getCause());
    

    inside catch block E.g.

       try {
            demo();
        }
        catch(ArithmeticException e) {
            //display top_level exception
            System.out.println("Cautch : " + e);
            System.out.println("Main Cause : " + e.getCause());
        }