Reputation: 1139
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){
}
Upvotes: 6
Views: 7087
Reputation: 392
The cause value is the cause of this throwable exception. To make getCause() return a value you can check an example of my peace of code.
class Dog {
public void makeSound() {
System.out.println("Bark Bark");
throw new NullPointerException("message");
}
}
try {
// create an object of Dog
Dog dog = new Dog();
// create an object of Class
// using getClass()
Class obj = dog.getClass();
// using object of Class to
// get all the declared methods of Dog
Method[] methods = obj.getDeclaredMethods();
// create an object of the Method class
for (Method m : methods) {
Object[] parameters = new Object[] {};
m.invoke(dog, parameters);
}
} catch (InvocationTargetException e) {
System.out.println(e);
} catch (Exception ex) {
System.out.println(ex);
}
FYI:
e.getTargetException()
is the same as e.getCause()
InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor.
InvocationTargetException DOC link
Some related info Chained Exceptions
Upvotes: 0
Reputation: 95978
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);
}
Upvotes: 5