Question

What rules applies to the following code:

    try {
        assert (false) : "jane";
    } catch (Exception e2) {
        System.out.print("ae2 ");
    } finally {
        throw new IllegalArgumentException();
    }

Assetions are enabled.

Why IllegalArgumentException is reported instead of AssertionError? Are there any rules which applies in this situations?

Edit: Sorry! in this example there should be assert (false)

Was it helpful?

Solution

An uncaught exception in a finally block (or in a catch block) causes any exception from the try block to be discarded. See the Java Language Specification § 14.20 for details. As of Java 7, an enclosing try/catch block can recover discarded exceptions (as described here).

OTHER TIPS

finally block always runs. The assert evaluates to true, so the finally block throws the exception.

Also, assertions are disabled by default anyway, which might be the reason why the assertion never got evaluated.

p.s

If the assert evaluates to false, finally will run anyway and throw the Exception, instead the AssertionError.

Remember finally block always runs, except when the JVM halts in the try block.

The only line which does anything is

throw new IllegalArgumentException();

whereas

assert true

doesn't do anything and even if it did it wouldn't be caught by catch(Exception

The finally block will always be executed. The only situation in which it won't be executed is a JVM shutdown (i.e. System.exit(-).)

What you might find interesting is that even if you'd have:

try { 
    return ...; 
} 
finally { 
    ...
}

the finally block will still be executed, and it will be executed before the method exits.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top