1

我在调用getCause.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时,它会打印以下输出

Inside testIt funtion.
null

但是在调试时,我可以看到原因私有变量的值设置ValidationException为预期的值,但是在调用该私有字段的 getter 时返回 null。

4

2 回答 2

3

ValidationException你抛出的将th在你的调用代码中......没有理由这样ValidationException。的重点getCause()是一个例外能够将另一个例外作为根本原因 - 但在您的情况下只有一个例外。

cause您看到私有变量的值的事实ValidationException完全符合该字段的记录方式(强调我的):

导致此 throwable 被抛出的 throwable,如果 throwable 不是由另一个 throwable 引起,或者原因 throwable 未知,则为 null。如果这个字段和这个 throwable 本身相等,说明这个 throwable 的原因还没有被初始化。

这就是为什么getCause()实现为:

return (cause==this ? null : cause);

如果您想查看预期的链接效果,您可以创建两个异常,一个链接到另一个:

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

现在调用getCause()ValidationException返回IllegalArgumentException.

您可能只想将调用代码更改为 logth而不是th.getCause()

于 2015-02-26T13:20:00.990 回答
2

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

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

于 2015-02-26T13:20:24.413 回答