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?
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)
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";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With