它是用Java设计的,如果我在Exception上调用getCause() ,则会得到Throwable对象。
我知道getCause()只是从Throwable继承的,我知道Throwable可以是Error或Exception ,但是程序员通常只应在Exception级别上工作,而不处理Throwable / Error类。
例如,在Java异常层次结构设计中是什么原因导致在Exception类中不包含getCause()会返回Exception对象?
这是从Java Concurrency in Practice (Brian Goetz)中摘录的不便之处:
public class Preloader {
private final FutureTask future =
new FutureTask(new Callable() {
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);
}
}
}
书中说:
...还因为ExecutionException的原因作为Throwable返回,因此不方便处理...
在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);
}