From the JLS
You can read about this in the JLS, Blocks and Statements, section "14.19.2 Execution of try-catch-finally". And I quote,
If execution of the try block completes abruptly for any other 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). The example...
Therefore, the following (which is really condensed from the questioner's code) completes with an NPE, not the ExceptionTest
thrown.
class Phinally
{
static class ExceptionTest extends Exception
{ public ExceptionTest(String message) { super(message); } }
public static void main(String[] args) throws ExceptionTest
{
try {
System.out.println("Foo.");
throw new ExceptionTest("throw from try");
} finally {
throw new NullPointerException("throw from finally");
}
}
}
A Sidebar about try
with resources/ARM blocks
Difficulties reasoning about this in some common cases specifically with managing resources, and requiring nested try
/catch
/finally
blocks, and nested inside finally
blocks, are part of the reason for the "try with resource" feature in project COIN (to be integrated into Java "fairly soon"), about which you can read more about here.
This is one of many good reasons to invest the time in running a static analyzer like PMD, which finds and complains about this type of confusion -- though it might not catch the case in your code, I'm not sure.
Static Checking
Follow up on comment from @stacktrace: I ran the relevant code through PMD and FindBugs, trying both of the following:
finally { throw NullPointerException("Foo"); }
and
finally { Object o = null; System.out.println(o.toString()); }
For the former, PMD noticed and complained about an exception being thrown from a finally
clause. FindBugs doesn't complain at all. For the latter, PMD complained about several things but nothing related ("LocalVariableCouldBeFinal", "StringToString", and "UselessOperationOnImmutable"). However, FindBugs noticed and complained about a null dereference. Moral of the story? Run both PMD and FindBugs!
Related
Related on SO: Swallowing exception thrown in catch/finally. Can I avoid such cumbersome try/catch/finally...