4

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)

mmatloka
  • 1,986
  • 1
  • 20
  • 46

4 Answers4

6

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.

Mechkov
  • 4,294
  • 1
  • 17
  • 25
1

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).

Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0

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

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • In that case, the answer is that finally is always executed last and replaces any previous action except `System.exit();` – Peter Lawrey Nov 23 '11 at 20:08
0

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.

Piotr Nowicki
  • 17,914
  • 8
  • 63
  • 82