`return value 'from constructor Exception in Java?

See what the following code snippet is:

A a = null try { a = new A(); } finally { a.foo(); // What happens at this point? } 

Suppose the constructor throws an exception at runtime. On the marked line, am I always guaranteed to get a NullPointerException, or will foo () be called on the semi-constructed instance?

+7
java instantiation exception
source share
4 answers

The code inside the try block contains two different operations:

  • Create a new instance of A
  • Assign a new instance to a variable named A

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

+12
source share

If new A() throws an exception, you will always get a NullPointerException because assigning a will not happen.

+6
source share

I think you will always get NPE on the marked line. The quest will never have the opportunity.

+1
source share

If a new A () exception is thrown in the constructor, then the time when the object has a null value. So a.foo () gives a null pointer exception. You can give a condition as if (a! = Null) {a.foo (); }

+1
source share

All Articles