它是用 Java 设计的,如果我在 Exception
上调用 getCause()
,我会得到一个 Throwable
对象。
我知道 getCause()
只是继承自 Throwable
并且我知道 Throwable
可以是 Error
或 Exception
,但程序员通常应该只在 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 aThrowable
, 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,您可以简单地调用
s.getCause()
并检查它是否是 Exception
的实例
关于java - 如果我在异常上调用 getCause(),为什么我必须处理 Throwable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31838296/