1

I am able to catch RuntimeException or subclass of it with below code:

try {
    //code that throws subclass of RuntimeException
    throw new ChildRuntimeException("try");
} catch (Exception ex) {
    System.out.println(ex.getMessage());
}

But I am getting error with below code and not able to catch RuntimeException in Exception catch block.

try {
    // code that throws subclass of Exception
    throw new ChildExceptionClass("try");
} catch (ChildExceptionClass ex) {
    throw new RuntimeException(ex.getMessage());
} catch (Exception ex) {
    System.out.println(ex.getMessage());
}

I searched for the same type of questions but did not find a suitable answer. Can anyone explain why the behaviour is different?

2 Answers 2

2

In the second example you are throwing a childRuntimeException, which is caught, but then a new runtimeException is thrown. This block has no "catch" clause, so the exception is thrown and not caught.

The second catch is relevant for the "try" block, not for the "catch" block.

Sign up to request clarification or add additional context in comments.

3 Comments

But we can catch RuntimeException also with catch(Exception ex) block, so why it was not caught in that, can you explain or any example you want to give?
No, I just want to understand why second code does not work because as per my understanding we can catch RuntimeException in catch block with Exception but not happening with multiple catch blocks at same time.
Second catch block which is part of multiple catch blocks, will be only used if the first one was not used.
1

What I guess you probably want to do is:

    try { // code that throws subclass of Exception
        throw new ChildExceptionClass("try");
    } catch (ChildExceptionClass ex) {
      try {
            throw new RuntimeException(ex.getMessage());
       } catch (Exception ex) {
        System.out.println(ex.getMessage());
       }   
    }

Do you understand the difference?

2 Comments

Does it mean I cant catch any Exception if it is thrown from catch block and it should be caught with another parent try/catch block or the caller method try/catch
Im not sure what do you mean. What I can say is that using a multiple catch blocks is working like this: if an exception is thrown from the "try" block, the first catch block is trying to be used. If the exception is caught, the other catch blocks will not be used (even if anothe rexception will be thrown from the catch block). If the exception is not caught, the second catch block will btried to be used, and so on. Hope it's clear now.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.