views:

85

answers:

4

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?

+11  A: 

The code inside the try block contains two distinct operations:

  1. Create a new A instance.
  2. 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.

SLaks
Therefore write it as `final A a = new A(); try { ... } finally { a.foo(); }`. And if it needs an exception caught add **another** try block around the lot.
Tom Hawtin - tackline
or if you are unsure of the state of the `a` reference in the finally block, just wrap `a.foo()` with `(if a!=null)`
matt b
+4  A: 

If new A() raises an exception, you'll always get a NullPointerException because the assignment to a won't happen.

Phil Ross
+1  A: 

I think you would always get an NPE at the marked line. The assignment never has a chance to occur.

slau
A: 

If the exception occured in the constructor call new A(),That time the object has null value.So the a.foo() gives the null pointer exception.you can give the condition as if(a!=null){ a.foo(); }

Arivu2020