Null Pointer exception within a try catch block

26,094

Solution 1

You should not use try / catch blocks to eliminate null pointer exceptions. Null pointer exceptions should be passed down, to let programmer know that problem arises and where.

In your case, you are catching IOException, so its not NullPointerException.

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

From this example, you can also see that its best to not execute lots of methods in one line:

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

its better to write:

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

this way you will know from callstack where NPE originated,

if your code is unsafe, like you know you can get nullpointer from some method, then simply check it:

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

Solution 2

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

     Log.e("your app", e.toString());
     break;
    }

Should solve the issue

Share:
26,094
Bachalo
Author by

Bachalo

Storyteller and constant beginner

Updated on January 23, 2020

Comments

  • Bachalo
    Bachalo over 4 years

    Getting the following runtime error, causing my application to crash on launch

    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 snippet

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

    Can anyone suggest next steps in trying to debug? I thought that use of a try catch block would eliminate any null pointer errors.

  • Eel Lee
    Eel Lee over 10 years
    "Should solve the issue" - not really, because NullPointer will still be there... this is ignoring a problem, not solving it.
  • Umer Farooq
    Umer Farooq over 10 years
    And do you know the purpose of Log.e()? That's there to tell what is the cause of Exception.
  • Bachalo
    Bachalo over 10 years
    thanks, although the answer below by marcin_j is more detailed, this helps a great deal.
  • Kenny Dabiri
    Kenny Dabiri over 7 years
    The break; is useless there @UmerFarooq