gpt4 book ai didi

java - 为什么不能使用 ExceptionInInitializerError 调用 initCause ?

转载 作者:行者123 更新时间:2023-11-30 03:50:29 25 4
gpt4 key购买 nike

为什么使用 initCause 调用 ExceptionInInitializerError 会产生 IllegalStateException

public class Test  {
public static final void main(String[] ignored) {
try {
ExceptionInInitializerError err = new ExceptionInInitializerError("1. Fail!");
err.initCause(new NullPointerException("null!"));
throw err;
} catch(Exception x) {
x.printStackTrace();
}

System.out.println();

try {
IllegalStateException isx = new IllegalStateException("2. Fail!");
isx.initCause(new NullPointerException("null!"));
throw isx;
} catch(Exception x) {
x.printStackTrace();
}

System.out.println();

try {
throw new IllegalStateException("3. Fail!", new NullPointerException("null!"));
} catch(Exception x) {
x.printStackTrace();
}
}
}

输出:

java.lang.IllegalStateException: Can't overwrite cause with java.lang.NullPointerException: null!
at java.lang.Throwable.initCause(Throwable.java:456)
at Test.main(Test.java:5)
Caused by: java.lang.ExceptionInInitializerError: 1. Fail!
at Test.main(Test.java:4)

java.lang.IllegalStateException: 2. Fail!
at Test.main(Test.java:14)
Caused by: java.lang.NullPointerException: null!
at Test.main(Test.java:15)

java.lang.IllegalStateException: 3. Fail!
at Test.main(Test.java:24)
Caused by: java.lang.NullPointerException: null!
... 1 more

我在文档中没有看到任何关于构造函数或类本身的内容,要么说(a)不允许,要么(b)为什么不允许。我确实在 JavaDoc 中看到了 "There is no saved throwable object.",但是,对我来说,这意味着可以设置一个。

这是“只是因为”,还是有其他原因导致您无法设置 ExceptionInInitializerError 的原因?

最佳答案

当我研究这个问题时,我正在查看ExceptionInInitializerError的源代码。

首先,class JavaDoc中有这个:

As of release 1.4, this exception has been retrofitted to conform to the general purpose exception-chaining mechanism. The "saved throwable object" that may be provided at construction time and accessed via the getException() method is now known as the cause, and may be accessed via the Throwable.getCause() method, as well as the aforementioned "legacy method."

没有任何关于“不要使用initCause”的内容,但这似乎是您将得到的最接近的结果。

constructors明确地使这成为不可能,并且内部注释比 JavaDoc 中的任何内容都清晰得多(只说“没有保存的可抛出对象”):

/**
<P>... There is no saved throwable object.</P>
**/
public ExceptionInInitializerError() {
initCause(null); // Disallow subsequent initCause
}
public ExceptionInInitializerError(Throwable thrown) {
initCause(null); // Disallow subsequent initCause
this.exception = thrown;
}
public ExceptionInInitializerError(String s) {
super(s);
initCause(null); // Disallow subsequent initCause
}

不太明白真正的原因,但它似乎是无法改造的遗留代码和“只是因为”的混合体。

关于java - 为什么不能使用 ExceptionInInitializerError 调用 initCause ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24599884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com