Reputation: 61
I've tried calling this on exceptions universally and by default throughout my application:
String causeClass = e.getCause().getClass().getName();
But I'm getting NullPointerException
s.
Is there a safe way to look for a cause and get the class name of the cause exception?
Upvotes: 6
Views: 2983
Reputation: 91349
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)
Upvotes: 8
Reputation: 4989
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";
}
}
Upvotes: 4
Reputation: 48596
As your outcome shows, some Exception
s (and some Throwable
s in general) do not have a cause. As stated in the docs:
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.)
As JG points out, printStackTrace()
is a good alternative.
Upvotes: 1