Bech on Enterprise Java
Thursday, June 16, 2005
  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!
 
Comments:
hmm fine - but
how do you avoid the message
"The local variable o may not have been initialized"
my compiler gives?
 
Sorry, that was my fault. The code is supposed to look like this ; I've updated my blog entry. Thanks for noticing!

public void good() {
Object o ;
try {
o = new String("testing");
} catch (Exception someException) {
someException.printStackTrace();
throw new RuntimeException("Oh Oh.....");
}
o.toString() ;
}
 
The compiler error demonstrates the value of the style.

I be that was deliberate.
 
Post a Comment



<< Home
I hereby promise to blog my thoguhts and views on Enterprise java, design patterns, frameworks and all other things that make life as a software developer interesting.

Name:
Location: Oslo, Oslo, Norway

www.glennbech.com

ARCHIVES
May 2005 / June 2005 / July 2005 / January 2006 / February 2006 / June 2006 / July 2006 / August 2006 / October 2006 / November 2006 / March 2007 /


Powered by Blogger