0

What is the best way to handle a NullPointerException coming from a Throwable catch.

public void run() {
    try{

    }catch (Throwable e){

        // e.getMessage() is equal to null 
        // and sends a NullPointerException
        if (e.getMessage().equals(“something“){

        }
    }
}

Making some research I found here that the JIT compiler will optimize away stack traces in certain exceptions if they happen enough

I thought I can throw an Exception inside the Throwable catch, but it doesn’t look clean.

Thanks!

Pompeyo
  • 1,459
  • 3
  • 18
  • 42
  • 3
    the best way is to check if the object is actually null. Catch it, is in my opinion, *wrong and dangerous* – Blackbelt Jul 28 '14 at 13:57

1 Answers1

2

Don't write code that may throw NullPointerException.

public void run() {
    try {

    } catch (Throwable e){

        if (“something“.equals(e.getMessage()) {

        }
    }
}

or

public void run() {
    try {

    } catch (Throwable e){

        if (e.getMessage() != null && e.getMessage().equals(“something“) {

        }
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768