Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwable getCause returns null

Tags:

java

throwable

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){
}
like image 464
yuris Avatar asked Apr 07 '14 06:04

yuris


People also ask

Can getCause be null?

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.

What is throwable getCause?

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.


1 Answers

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);
}
like image 146
Maroun Avatar answered Oct 22 '22 22:10

Maroun