在Java中捕获Throwable的最佳做法 [英] Best practices for catching Throwable in Java

查看:1280
本文介绍了在Java中捕获Throwable的最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,你只需要抓住Throwable,例如当编写调度通用项目的调度程序队列并需要从任何错误中恢复时(所述调度程序记录所有捕获到的异常,但默默地记录,然后在其他项目上继续执行)。



我可以想到的一个最佳做法是总是重新抛出异常,如果它是InterruptedException,因为这意味着有人中断了我的线程并想要杀死它。



另一个建议(来自评论,而不是答案)是始终重新推荐

可能最重要的一个是,永远不会吞噬被检查的异常。这个意思是不要这样做:

  try {
...
} catch IOException e){
}

除非这是你打算 。有时候,人们会检查异常,因为他们不知道该怎么办,或者不想(或不能)用throws Exception子句污染他们的界面。



如果您不知道该怎么做,请执行以下操作:

  try {
..
} catch(IOException e){
throw new RuntimeException(e);
}

另一个令人想到的是确保处理异常。读取文件应如下所示:

  FileInputStream in = null; 
尝试{
in = new FileInputStream(new File(...));;
//做东西
} catch(IOException e){
//适当处理
} finally {
if(in!= null)try {in 。关(); } catch(IOException e){/ *吞下这一个* /}
}


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 */ }
}

这篇关于在Java中捕获Throwable的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆