user2953119
user2953119

Reputation:

Throw an exception in the finally block

I've tried to throw the same excpetion in a finally block, while the previously throwed expcetion was not catched. I expected that we have two object of Excpetion type that shal be thrown. Since we need in two catch clauses as the following:

public static void main(String[] args) {
    try {
        try {
            try {
                throw new Exception();
            } finally {
                System.out.println("finally");
                throw new Exception();
            }
        } catch (Exception ex) {
            System.out.println("catch");
        } finally {
            System.out.println("finally");
        }
    } catch (Exception ex) {
        System.out.println("catch");
    }
    System.out.println("finish");
}

But that program prints:

finally
catch
finally
finish

That is, the second catch clause was not entered. Why?

Upvotes: 1

Views: 1542

Answers (3)

Jens Schauder
Jens Schauder

Reputation: 81907

When you throw an exception in the finally block, the first exception silently disappears.

It's in the JLS Chapter 14.20.2

If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S.

This is true how ever you entered the finally block. If you entered it by throwing an exception T that exception can not be catched anymore.

Upvotes: 4

Juxhin
Juxhin

Reputation: 5600

Your first try-catch is already trying to catch it, the extra try blocks aren't there for any particular reason. If you try to throw more exceptions you'll notice that you'll get a syntax error, Unreachable code

Basically, keep it in one try block

Upvotes: 0

Eran
Eran

Reputation: 393821

When you throw an exception from the finally block, it supresses any exception thrown from the try block, therefore there was only one exception to catch.

The first catch cluase already caught that exception, so the second one had nothing to catch.

Upvotes: 0

Related Questions