Wednesday, April 15, 2009

How to avoid annoying NullPointerException

Hi All,

Today, I want to discuss how can we avoid this "NullPointerException". This NullPointerException is very annoying and we have to use too much try/catch statements to control the behavior of this Exception.

Normally, when defining any variable in the methods we have to initialize them and we initialize them to Null, if it is an object type variable.

I am writing one phesdocode to represent this behavior.

public void hello(){

Aobject a = null;

// do some operations

if(){

// do something

a = some value assigned to it
} else {

// on else condition

a = new Aobject();
}

return a;
}

In this way when we use this method in any combinition, we'll never have NullPointerException rather if there is no value u will get empty object.

It will improve the performance what I believe so. If someone disagree with this, please do comment and give us the best way to avoid this NullPointerException.

Regards

No comments: