java - 如果我在异常上调用 getCause(),为什么我必须处理 Throwable

标签 java exception

它是用 Java 设计的,如果我在 Exception 上调用 getCause(),我会得到一个 Throwable 对象。

我知道 getCause() 只是继承自 Throwable 并且我知道 Throwable 可以是 ErrorException,但程序员通常应该只在 Exception 级别上工作,而不处理 Throwable/Error 类(class)。

Java 异常层次结构设计的原因是什么,例如,Exception 类中不包含 getCause() 会返回 Exception 对象?

这是从 Java 并发实践 (Brian Goetz) 中获取的不便示例:

public class Preloader {
    private final FutureTask<ProductInfo> future =
        new FutureTask<ProductInfo>(new Callable<ProductInfo>() {
            public ProductInfo call() throws DataLoadException {
                return loadProductInfo();
            }
        });
    private final Thread thread = new Thread(future);
    public void start() { thread.start(); }
    public ProductInfo get()
        throws DataLoadException, InterruptedException {
        try {
            return future.get();
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof DataLoadException)
                throw (DataLoadException) cause;
            else
                throw launderThrowable(cause);
        }
    }
}

书上说:

...but also because the cause of the ExecutionException is returned as a Throwable, which is inconvenient to deal with...

并且在 launderThrowable() 中处理立即重新抛出 Error(因为我们不想处理它)并返回 RuntimeException:

public static RuntimeException launderThrowable(Throwable t) {
    if (t instanceof RuntimeException)
        return (RuntimeException) t;
    else if (t instanceof Error)
        throw (Error) t;
    else
        throw new IllegalStateException("Not unchecked", t);
}

最佳答案

getCause 是在Throwable 中定义的方法,在Exception 中简单地继承Throwable 的原因只是一个Throwable(它可能是一个Exception 或一个Error)。

IMO,有一个方法,比如 getCauseAsException,它只返回一个 Exception,如果有的话作为原因异常并不是很有用。如果您只关心 Exception 而不是 Error,您可以简单地调用 getCause() 并检查它是否是 Exception 的实例s.

关于java - 如果我在异常上调用 getCause(),为什么我必须处理 Throwable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31838296/

相关文章:

java - 通过 JSch 连接到服务 - 预期数据包类型 30,得到 34

java - 必须实现抽象方法

java - 了解 JUnit 5 中的异常测试

macos - 核心数据抛出 NSInternalInconsistencyException "The context is still dirty after 100 attempts."

python 2 : what is the best way to obtain information during an exception?

java - JSlider 在 10 秒后隐藏,就像在电视机中一样

java - 在抽象基类中使用 Java 泛型

java - 可以将 Intent 的 startActivityForResult() 中使用的请求代码用作常规变量吗?

c# - 在私有(private)委托(delegate)方法中测试异常

javascript - 如何从图像加载中捕获异常