There is a class X.
A method method() in X class throws SomeException.
I wonder which method of handling exceptions is better – more efficient. If it is surrounding try-block method throwing exceptions and all dependencies or keeping dependences outside try-block, but returning from method after failure.
1.
public void test() {
X x = new X();
try {
T temp = tx.method();
temp.doWhatever();
}
catch(SomeException e) { handleException(e); }
}
or
2.
public void test() {
X x = new X();
T temp = null;
try {
temp = tx.method();
}
catch(SomeException e) {
handleException(e);
return;
}
temp.doWhatever();
}
Edited: (after your annotations)
What is more I undersand my code like that:
1.
tx.method() will throw an exception so the next thing which will be excetuted is catch– block. It doesn’t matted that temp is still null because program skips temp.doWhatever(); line and there will be no NullPointerException.
2.
Here I use return instruction because I don’t want to execute temp.doWhatever() because temp is null
The second case won’t even compile (and it does not even make sense), as
tempis not visible outside thetryblock. In any case, I would go for this:Since if initializing
tempfails, the rest of thetempoperations should not execute.