Saturday, August 9, 2008

Null Pointer Exception

When you encounter a NULL pointer exception ( Null pointer exception is the exception that is thrown by the JVM when you perform some operation on an object which is null or calling some method on the object that is null), you should not try to handle that exception i.e., DONT try ...catch the null pointer exception. It is nothing but patching the problem and it isin't the right way. You should try to avoid performing any operation on null object.

Eg:

object.method();

Assume this statement generates a null pointer exception.

Wrong method :

try {
object.method();
} catch ( Exception Ex) {
// handle the exception
}

Correct Method :

if ( object != null) {
object.method();
}

No comments: