Throwable类的getCause()函数(在Java中)没有按预期工作

时间:2015-02-26 13:16:32

标签: java exception null throwable

调用getCause的{​​{1}}函数时,我变为空。

Throwable

在运行package com.salman.demo; public class MyClass { public static void main(String[] args) { // TODO Auto-generated method stub try { NormalClass.testIt(); } catch (Throwable th) { System.out.println(th.getCause()); } } } package com.salman.demo; import com.salman.exceptions.ValidationException; public class NormalClass { public static void testIt() throws ValidationException { System.out.println("Inside testIt funtion."); throw new ValidationException("Validation Exception.."); } } 时,它会打印以下输出

MyClass

但是在调试时,我可以看到cause私有变量的值设置为Inside testIt funtion. null 这是预期的,但是当调用该私有字段的getter时返回null。

2 个答案:

答案 0 :(得分:2)

您投放的代码中ValidationException thValidationException ... <{em> getCause()cause的要点是一个例外,可以将另一个例外作为根本原因 - 但在您的情况下只有一个例外。

您认为私有ValidationException变量的值为getCause()这一事实完全符合该字段的记录方式(强调我的):

  

导致抛出此throwable的throwable,如果抛出则抛出null   throwable不是由另一个throwable引起的,或者是因为致使   扔掉的是未知的。 如果此字段等于此throwable本身,   它表明这个throwable的原因尚未发生   初始化。

这就是为什么return (cause==this ? null : cause); 被实现为:

throw new ValidationException("Validation Exception..",
    new IllegalArgumentException("Bang!"));

如果你想看到有效的链接,你可以创建两个例外,一个链接到另一个:

getCause()

现在在ValidationException上调用IllegalArgumentException将返回th

您可能只想更改您的调用代码,以便记录th.getCause()而不是{{1}}。

答案 1 :(得分:2)

您的例外是链中的第一个,因此它没有原因。

如果你想测试,你需要拥有异常链,所以你要抓住它并抛出一个使用前一个构造的新的。