I'm working on a legacy system and to simulate some behavior I tried simpler pieces of code, like this one, to understand exception handling (the legacy system uses lots of user exceptions). I know throwing exceptions at finally
block is undesired, but my goal was to understand current behavior, not develop some improvements.
public class ExceptionTest {
public static void loopUntil10() {
for (int i = 0; i < 10; i++) {
if (i == 7) {
System.out.println("7!");
throw new NullPointerException("7");
}
if (i == 8)
System.out.println("8");
}
}
@SuppressWarnings("finally")
public static void main(String[] args) {
try {
System.out.println("1");
ExceptionTest.loopUntil10();
throw new NullPointerException("2");
} catch (Exception e) {
System.out.println("3");
throw new NullPointerException("4");
} finally {
System.out.println("5");
throw new NullPointerException("6");
}
}
}
With this I thought it should print
1
followed by7!
, I think this was no surprise- since
NPE("7")
will be thrown, execution would go to catch block, printing3
and throwingNPE("4")
- after catch block finishes, finally block would print
5
and throwNPE("6")
Although I don't know what happens to exceptions 7 and 4,it prints like planned:
1
7!
3
5
Exception in thread "main" java.lang.NullPointerException: 6
at ExceptionTest.main(ExceptionTest.java:26)
But sometimes it gets weird:
Is this a weird Eclipse behavior ou some Java Exception concept I'm missing? Are 7
and 4
exceptions lost? I mean, there's any trace they were called sometime?