Java SE: Avoiding NullpointerExceptions by not initializing local variables to null
I'm sure this is fairly obvious to a lot of experienced programmers. However, having not paid enoght attention to the small details this was recently pointed out for me (emberrasingly enough!) It's now a part of my "good coding practices".
In this piece of code we might get a NullPointerException at the 0.toString(). This happens if an exception is thrown inside the try/catch block We shold have logged the event and terminatet the flow of execution in the catch block, but forgot to do so!
public void bad() { Object o = null; try { o = callSomeMethod(); } catch (Exception someException) { someException.printStackTrace(); } o.toString() ; }This code compiles, but will result in a nullpointer exception when in the cases where someMethod throws someException.
Situations like this can easily be avoided by not initializing the variable o to null. In this piece of code we not NOT initialize the object o, and get a compiler error at the .toString() method call, because there is a change that the variable 'o' has not been initialized.
public void good() {
Object o ;
try {
o = callSomeMethod(); } catch (Exception someException) {
someException.printStackTrace();
}
o.toString() ;
}
By avoiding initializing local varibales to null, we can avoid some of those NullpointerExceptions, and get more robust code!