java getcause_java - 如果在异常上调用getCause(),为什么还要处理Throwable - 堆栈内存溢出...

它是用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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值