`return value' from Constructor Exception in Java?

exception, instantiation, java

Solution

The code inside the `try` block contains two distinct operations:

- Create a new `A` instance.

- Assign the new instance to a variable named `a`.

If an exception is thrown in step 1, step 2 will not be executed. Therefore, you will always get a `NullPointerException`.

Problem

Take a look that the following code snippet: ``` A a = null try { a = new A(); } finally { a.foo(); // What happens at this point? } ``` Suppose A's constructor throws a runtime exception. At the marked line, am I always guaranteed to get a NullPointerException, or foo() will get invoked on a half constructed instance?

Original source