Monday, November 21, 2005

Null Pointer Exception

Right now, I'm doing my project in SUN Microsystems. An interesting thing that i learned here with respect to null pointer exception in Java language is as follows:

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();
}

9 comments:

  1. NullPointerException is just of the unchecked exceptions in java.
    don't u think the try-catch block is a bad design for any unchecked exception for that matter.
    or there is some peculiarity with NullPointerException ?

    ReplyDelete
  2. Generating a null pointer in the code is really avoidable and have to be avoided rather than catching. so...in industry practice, when we use try catch for null pointer , we call that as patching ....not debugging....so...this holds best...for nullpointer exception ... so..in my opinion, i think...this one holds good only for null pointer exception kapil!

    ReplyDelete
  3. Thank you so much!! You just saved my homework!

    ReplyDelete
  4. thank you sooooooo veryyyyyyyyy much..

    ReplyDelete
  5. HI i experienced such a exception and ur method dint solve it..

    ReplyDelete
  6. Here s my code..

    ((JButton)(getComponent( 2 ).getAccessibleContext().getAccessibleChild( 3 ).getAccessibleContext().getAccessibleChild( 1 ))).setVisible(false);

    Applying as u said,,

    if(getComponent(2)!=null)
    {
    ((JButton)(getComponent( 2 ).getAccessibleContext().getAccessibleChild( 3 ).getAccessibleContext().getAccessibleChild( 1 ))).setVisible(false);
    }

    but this dint solve it.. it throws NullPointerException

    ReplyDelete
  7. @Javs
    I think getAccessibleContext() might be returning null. May be you can use null check there!

    ReplyDelete
  8. THIS IS SPARTA!!!

    ReplyDelete
  9. Yes you are right that NullPointerException is thrown by JVM but I don't agree that you should not use try-catch block for this kind. According to me your condition of checking (obj!=null){...} is actually a bug ! Always use try-catch and do e.printStackTrace();
    to find out the cause and fix it. Null pointer is actually a dangerous thing and should not be ignored if it is there because it can always be removed.

    ReplyDelete