Java – try null pointer exception in catch block

try null pointer exception in catch block… here is a solution to the problem.

try null pointer exception in catch block

Getting the following runtime error that caused my app to crash on startup

E FATAL EXCEPTION: MonitoringThread 13533 AndroidRuntime E
Process: foo.com, PID: 13533 13533 AndroidRuntime E
java.lang.NullPointerException 13533 AndroidRuntime E at
foo.com$MonitoringThread.run(foo.java:125) 13533
AndroidRuntime E at java.lang.Thread.run(Thread.java:841)

The offending line is

ret = mConnection.getInputStream().read(buffer);

In the following code fragment

try {
    ret = mConnection.getInputStream().read(buffer);
    } catch (IOException e) {
    break;
    }

Can anyone suggest the next steps to try debugging?
I think using try catch block eliminates any null pointer errors.

Solution

You should not use try/catch blocks to eliminate null pointer exceptions. Null pointer exceptions should be passed down to let the programmer know where the problem is.

In your case, you are capturing IOException, so it is not a NullPointerException.

Also check what is the null that caused this exception, maybe its mConnection? or getInputStream() returns null.

As you can also see from this example, it’s better not to execute many methods in one line:

ret = mConnection.getInputStream().read(buffer);

It is better to write like this:

InputStream is = mConnection.getInputStream();
ret = is.read(buffer);

This way you can know from the call stack where the NPE originated

If your code is not safe, like you know you can get a null pointer from some method, then just check it:

InputStream is=null;
if ( mConnection != null ) {
   is = mConnection.getInputStream();
   if ( is != null ) {
     ret = is.read(buffer);
   }
   else {
       log error?
   }
} 
else {
    log error?
}

Related Problems and Solutions