Java 为什么InvocationTargetException设计为将其原因存储为目标?

Java 为什么InvocationTargetException设计为将其原因存储为目标?,java,error-handling,Java,Error Handling,我想知道为什么InvocationTargetException被设计为将其原因存储为目标,要求每个人通过InvocationTargetException.getTargetException()而不是InvocationTargetException.getCause()来打开它。这是由于记录不完整/错误的堆栈跟踪而导致错误处理的最常见情况之一。在java语言中,这似乎是一个糟糕的设计决策,或者这种设计的目的是什么?您似乎有一种误解,即getCause返回的值与getTargetExcept

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

您似乎有一种误解,即
getCause
返回的值与
getTargetException
返回的值不相同,因为它返回的值相同。只是早期Java版本中不存在
getCause
InvocationTargetException
自Java1.1以来就已经存在,而一般异常链接仅在Java1.4中引入

引用(我的):

从1.4版开始,此异常已进行了改装,以符合通用异常链接机制。在构造时提供并通过
getTargetException()
方法访问的“目标异常”现在称为原因,可以通过
Throwable.getCause()
方法以及前面提到的“遗留方法”访问。

和文件(我的重点):

获取抛出的目标异常

此方法早于通用异常链接工具现在首选使用
Throwable.getCause()
方法获取此信息。

如果查看
getCause
getTargetException
的实现,它们具有相同的实现:

/**
*获取抛出的目标异常。
*
*此方法早于通用异常链接工具。
*{@link-Throwable#getCause()}方法现在是首选的方法
*获取此信息。
*
*@返回引发的目标异常(此异常的原因)。
*/
公共可丢弃的getTargetException(){
回报目标;
}
/**
*返回此异常的原因(引发的目标异常,
*可以是{@code null})。
*
*@返回此异常的原因。
*@自1.4
*/
公众可丢弃的getCause(){
回报目标;
}

实际上,从1.1开始,1.0中就没有反射。@EJP谢谢,编辑了它。因为自从之后就没有了
,所以我认为它在Java 1.0中已经存在了。你是对的,似乎我的记忆在这方面有点不稳定,我记得前一段时间我不得不特别处理InvocationTargetException,但也许我错了。我现在看到的InvocationTargetException的唯一问题是.initCause(cause)不能正常工作,因为它不能覆盖目标异常。
/**
 * 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;
}