With the following code:
try {
throw new RuntimeException ("main");
}
finally {
throw new RuntimeException ("finally");
}
I get this result:
Exception in thread "main" java.lang.RuntimeException: finally
at test.main(test.java:12)
However, with the addition of suppressed exceptions in Java 7, wouldn't it be logical for the language to register original "main" exception as suppressed when finally
block itself fails with exception? Currently I have to manually emulate this:
try {
throw new RuntimeException ("main");
}
catch (RuntimeException exception) {
try {
throw new RuntimeException ("finally");
}
catch (RuntimeException exception2) {
exception2.addSuppressed (exception);
throw exception2;
}
}
to receive more useful (for understanding what's going on) result:
Exception in thread "main" java.lang.RuntimeException: finally
at test.main(test.java:13)
Suppressed: java.lang.RuntimeException: main
at test.main(test.java:9)
EDIT: To clarify what I'm wondering. Current Java version is 8, suppressed exceptions are not a brand new feature. But try..finally
still doesn't incorporate them. Is there something that prevents this from happening?
Because try-with-resources is syntactic sugar and the Java compiler doesn't expand regular try-finally blocks in the same way.
Take a look at the following code:
When compiled and then decompiled (using IntelliJ IDEA) it looks like this:
Whereas this code:
Looks exactly the same when compiled and decompiled.
Now, the case could definitely be made that all
finally
blocks should be expanded in the same way as is done above, but for some reason that has either been overlooked or decided against.I suggest you open a feature request for this because I think it's a sensible feature.