Correction of exceptions and errors

What rules apply to the following code:

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

Actions allowed.

Why is an IllegalArgumentException thrown instead of an AssertionError? Are there any rules that apply in these situations?

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

+4
source share
4 answers

An uncaught exception in the finally block (or in the catch ) throws any exception from the try block. For more information, see Java Language Specification ยง 14.20 . Starting with Java 7, a nested try / catch block can throw discarded exceptions (as described here ).

+1
source

finally always executed. assert is true, so the finally block throws an exception.

In addition, assertions are still disabled by default, which may be the reason that the assertion has never been evaluated.

ps

If assert is false, finally will work anyway and throw an exception instead of AssertionError .

Remember that the finally block always starts, unless the JVM stops in the try block.

+6
source

The only line that does anything

 throw new IllegalArgumentException(); 

then

 assert true 

does nothing, and even if it were done, it would not have been caught catch(Exception

0
source

The finally block will always be executed. The only situation in which it will not be will be the shutdown of the JVM (i.e. System.exit(-) .)

What may seem interesting to you is that even if you had:

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

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

0
source

Source: https://habr.com/ru/post/1382746/


All Articles