gpt4 book ai didi

java - 为什么 InvocableTargetException 被设计为将其原因存储为目标?

转载 作者:行者123 更新时间:2023-11-30 07:09:33 24 4
gpt4 key购买 nike

我想知道为什么 InvocableTargetException 被设计为将其原因存储为目标,要求每个人都通过 invocateTargetException.getTargetException() 而不是 invocateTargetException.getCause 来解包它()。这是通过记录不完整/错误的堆栈跟踪而导致错误处理最常见的情况之一。这在java语言中似乎是一个糟糕的设计决策,或者说这个设计的目的是什么?

最佳答案

您似乎有一个误解,认为 getCause 不会返回与 getTargetException 相同的值,因为它确实返回相同的值。只是早期的 Java 版本中不存在 getCauseIncationTargetException 自 Java 1.1 起就已存在,而一般异常链仅在 Java 1.4 中引入。

引自InvocationTargetException (强调我的):

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

InvocationTargetException.getTargetException()文档(强调我的):

Get the thrown target exception.

This method predates the general-purpose exception chaining facility. The Throwable.getCause() method is now the preferred means of obtaining this information.

如果您查看 getCausegetTargetException 的实现,您会发现它们具有相同的实现:

/**
* Get the thrown target exception.
*
* <p>This method predates the general-purpose exception chaining facility.
* The {@link Throwable#getCause()} method is now the preferred means of
* obtaining this information.
*
* @return the thrown target exception (cause of this exception).
*/
public Throwable getTargetException() {
return target;
}

/**
* Returns the cause of this exception (the thrown target exception,
* which may be {@code null}).
*
* @return the cause of this exception.
* @since 1.4
*/
public Throwable getCause() {
return target;
}

关于java - 为什么 InvocableTargetException 被设计为将其原因存储为目标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39438664/

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