繁体   English   中英

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

[英]getCause() function of Throwable class (in Java) is not working as expected

我在调用ThrowablegetCause函数时得到null。

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

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

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!"));

现在在ValidationException上调用getCause()将返回IllegalArgumentException

您可能只想更改您的调用代码以登录th而不是th.getCause()

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

如果要测试,则需要具有异常链,因此请阻止其中的一个并抛出使用前一个构造的新异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM