I am catching a Throwable
error.
catch (Throwable t){
System.out.println(t.getCause().getMessage());
}
When I put a breakpoint on a line System.out.
, and hover over (Eclipse) the t
variable, Eclipse shows me the cause: java.lang.NoClassDefFoundError: myclass
But when I release the breakpoint I am getting null
for t.getCause()
.
Why does it happen? How can I get the cause string.
UPDATE:
Same happens if I catch
catch (NoClassDefFoundError e){
}
There are cases where both getCause() and getMessage() will be null. The only good solution is to understand what exception types are going to be thrown and handle them gracefully.
The getCause() method of Throwable class is the inbuilt method used to return the cause of this throwable or null if cause can't be determined for the Exception occurred. This method help to get the cause that was supplied by one of the constructors or that was set after creation with the initCause(Throwable) method.
The answer is in the docs - 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.)
So when you do:
t.getCause().getMessage()
It's like writing:
null.getMessage()
Which of course causes NullPointerException
.
You can simply do:
catch (NoClassDefFoundError e){
System.out.println(e.getMessage);
}
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