[英]Throwable getCause returns null
I am catching a Throwable
error.我遇到了一个
Throwable
错误。
catch (Throwable t){
System.out.println(t.getCause().getMessage());
}
When I put a breakpoint on a line System.out.
当我在
System.out.
, and hover over (Eclipse) the t
variable, Eclipse shows me the cause: java.lang.NoClassDefFoundError: myclass
, 和 hover over (Eclipse)
t
变量,Eclipse 告诉我原因: java.lang.NoClassDefFoundError: myclass
But when I release the breakpoint I am getting null
for t.getCause()
.但是当我释放断点时,我得到了
null
t.getCause()
的 null 。
Why does it happen?为什么会这样? How can I get the cause string.
我怎样才能得到原因字符串。
UPDATE:更新:
Same happens if I catch如果我抓住也会发生同样的情况
catch (NoClassDefFoundError e){
}
The answer is in the docs - Throwable#getCause
: 答案在文档中 -
Throwable#getCause
:
Returns the cause of this throwable or
null
if the cause is nonexistent or unknown.返回此throwable的原因,如果原因不存在或未知,则返回
null
。 (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
. 这当然会导致
NullPointerException
。
You can simply do: 你可以简单地做:
catch (NoClassDefFoundError e){
System.out.println(e.getMessage);
}
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.
要使 getCause() 返回一个值,您可以查看我的代码和平示例。
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()
仅供参考:
e.getTargetException()
与e.getCause()
相同
InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor. InvocationTargetException 是一个已检查的异常,它包装了由调用的方法或构造函数抛出的异常。
InvocationTargetException DOC link InvocationTargetException 文档链接
Some related info Chained Exceptions一些相关信息链式异常
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.