I have a small theoretical problem with try-catch constructions.
I took a practical exam yesterday about Java and I don't understand following example:
try {
try {
System.out.print("A");
throw new Exception("1");
} catch (Exception e) {
System.out.print("B");
throw new Exception("2");
} finally {
System.out.print("C");
throw new Exception("3");
}
} catch (Exception e) {
System.out.print(e.getMessage());
}
The question was "what the output will look like?"
I was pretty sure it would be AB2C3, BUT suprise suprise, it's not true.
The right answer is ABC3 (tested and really it's like that).
My question is, where did the Exception("2") go?
From the Java Language Specification 14.20.2.:
If the catch block completes abruptly for reason R, then the finally block is executed. Then there is a choice:
If the finally block completes normally, then the try statement completes abruptly for reason R.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
So, when there is a catch block that throws an exception:
try {
// ...
} catch (Exception e) {
throw new Exception("2");
}
but there is also a finally block that also throws an exception:
} finally {
throw new Exception("3");
}
Exception("2")
will be discarded and only Exception("3")
will be propagated.