Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException: Does not every exception contain a cause?

I've tried calling this on exceptions universally and by default throughout my application:

String causeClass = e.getCause().getClass().getName();

But I'm getting NullPointerExceptions.

Is there a safe way to look for a cause and get the class name of the cause exception?

like image 536
Bill Avatar asked Aug 03 '11 20:08

Bill


2 Answers

As JustinKSU pointed out, sometimes there is no cause. From Throwable#getCause():

Returns the cause of this throwable or null if the cause is nonexistent or unknown. (The cause is the throwable that caused this throwable to get thrown.)

When this happens, getCause() returns null, therefore throwing a NullPointerException when you invoke getClass(). Perhaps you can use this instead:

Throwable t = e.getClause();
String causeClass = t == null ? "Unknown" : t.getClass().getName(); 

However, for debugging purposes, I find e.printStackTrace() to be much better. This way, you can see where exactly is the exception being thrown. Here is a typical output from printStackTrace():

 java.lang.NullPointerException
         at MyClass.mash(MyClass.java:9)
         at MyClass.crunch(MyClass.java:6)
         at MyClass.main(MyClass.java:3)
like image 65
João Silva Avatar answered Sep 20 '22 23:09

João Silva


The stack trace is different than the cause. If you create an exception

new Exception("Something bad happened")

There is no cause.

If however, you create an exception passing in another exception, then there will be a cause. For example:

try {
    //do stuff
} catch (IOException ie) {
    throw new Exception("That's not good", ie);
} 

Then ie will be the cause.

If you are trying to determine which class throw the exception you can do something like this:

public static String getThrowingClass(Throwable t){
    StackTraceElement[] trace = t.getStackTrace();
    if(trace != null && trace.length > 0){
        return trace[0].getClassName();
    } else {
        return "UnknownClass";
    }
}
like image 31
JustinKSU Avatar answered Sep 20 '22 23:09

JustinKSU