java throwable,在Java中捕获Throwable的最佳做法

Sometimes, you just have to catch Throwable, e.g. when writing a dispatcher queue that dispatches generic items and needs to recover from any errors (said dispatcher logs all caught exceptions, but silently, and then execution is continued on other items).

One best practice I can think of is to always rethrow the exception if it's InterruptedException, because this means someone interrupted my thread and wants to kill it.

Another suggestion (that came from a comment, not an answer) is to always rethrow ThreadDeath

Any other best practices?

解决方案

Probably the most important one is, never swallow a checked exception. By this I mean don't do this:

try {

...

} catch (IOException e) {

}

unless that's what you intend. Sometimes people swallow checked exceptions because they don't know what to do with them or don't want to (or can't) pollute their interface with "throws Exception" clauses.

If you don't know what to do with it, do this:

try {

...

} catch (IOException e) {

throw new RuntimeException(e);

}

The other one that springs to mind is to make sure you deal with exceptions. Reading a file should look something like this:

FileInputStream in = null;

try {

in = new FileInputStream(new File("..."));;

// do stuff

} catch (IOException e) {

// deal with it appropriately

} finally {

if (in != null) try { in.close(); } catch (IOException e) { /* swallow this one */ }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值