繁体   English   中英

为什么 Throwable.getCause 在返回 `null` 之前检查 'cause' 是否是 'this' 而不是直接返回 cause?

[英]Why does Throwable.getCause check to see if 'cause' is 'this' before returning `null` instead of just returning the cause directly?

今天我有理由进入Throwable.getCause的源代码,并且在该方法中看到此代码时有点惊讶:

    public synchronized Throwable getCause() {
        return (cause==this ? null : cause);
    }

这是来自 Java 1.8,但在我看过的更高版本中看起来相同。

我的问题是:为什么不简单地return cause并完成它?

它不是将causenull进行比较,而是将causethis进行比较。 为避免循环,如果causethis ,则返回 null。

编码:

 public synchronized Throwable getCause() {
     return (cause==this ? null : cause);
 }

说如果causethis返回null否则返回cause (它也可能是null因为它发生。

故事是这样开始的: private Throwable cause = this; 我相信所有版本>=1.4 都是一样的。 这将原因初始化为这个对象!

目的是Throwable对象是不可变的,但它提供了一个方法void initCause(Throwable cause)只能调用一次来初始化原因或由构造函数初始化的原因。

正如文档所解释的那样,允许将原因链接到在引入cause之前添加的子类,这些子类不包含在其构造函数之一中。

因此,该类以某种方式想知道是否已调用initCause并抛出IllegalStateException如果有)(我的评论):

public Throwable initCause(Throwable cause) {
    if (cause == this) //Illogical! An exception can't be self caused!
            throw new IllegalArgumentException();
    if (this.cause != this)// false if cause has been initialised 'properly'.
        throw new IllegalStateException();
    this.cause = cause;
     return this;
}

该类使用cause==this来指示未设置cause 它不能使用cause==null因为null是一个有效值。 所以它使用了cause==this的异常状态,因为主动设置causethis是自引发异常的不合逻辑状态。

它确实有效。 但这真的是个好主意吗? 我说不是。 它将“原因未设置”和“原因已设置并设置为null ”的状态混为一谈。 一个不太扭曲的设计只是引入了一个标志private boolean isCauseSet=false; 并在initCause被调用或设置它的构造函数被调用时设置它。

我们在Throwable看到的复杂代码只不过是避免了boolean Throwable保存单个boolean字段似乎真的不值得打扰。 没有任何有用的应用程序会在流通中拥有如此多的Throwable对象,因此它很重要。

null值由printStackTrace方法使用, 例如,在调用stackTraceString方法时,第 421..450行标识堆栈跟踪的输出应何时完成。

暂无
暂无

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

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