Search code examples
javaexceptiontry-catchfinallyclause

How to catch an exception that was thrown inside a catch clause?


try {

        throw new SomeException();

    }

    catch (SomeException e) {

        System.out.println("reached once");
        throw e;
    }

    catch (Exception e) {
        System.out.println("reached twice");
    }

This code only displays "reached once" even though the exception was thrown again inside the first catch clause. How can this be fixed in order that both catch clauses be executed?

PS: The above code was a general question I had, and I had to apply it to a much larger code with about 5 or 6 catch clauses that catch different exceptions, but in the end, at a certain point in a loop I need the exception to be thrown again.


Solution

  • Simply add another try catch in the catch.

    try {
        try {
    
            throw new NullPointerException();
    
        } catch (NullPointerException e) {
            System.out.println("reached once");
    
            throw e;
        }
    } catch (SomeOtherException ex) {}