Michael
Michael

Reputation: 14218

Is null in catch block required?

A a = null;
try {
  a = setA(); // set A throws exception
} catch (AException e) {
  a = null;
}

In the code above, do I need use a = null in the catch block to ensure that a is null if an exception occurs?

Upvotes: 2

Views: 116

Answers (2)

Alfergon
Alfergon

Reputation: 5909

If a method returning a value (in this case an object of class A) throws and exception, then it never returns a value.

As the line assigning a value to a is in this case said method, a never gets a value so null remains as the variable's value.

Upvotes: 2

wrm
wrm

Reputation: 1908

as the exception was thrown BEFORE the assignment in any case, i assume, that a will always be null here...

Upvotes: 3

Related Questions