Best practices for catching Throwable in Java

空扰寡人 提交于 2019-12-03 11:58:26

问题


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?


回答1:


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



回答2:


Depends on what you are working on.

if you are developing an API to be used by some one else, its better to re-throw the Exception or wrap it into a custom exception of yours and throw.

Whereas if you are developing an enduser application you need to handle this exception and do the needful.




回答3:


What about OutOfMemoryError (or perhaps its super class VirtualMachineError)? I can't imagine there is much you can do after something that serious.




回答4:


If you're writing a dispatcher queue, then by the time the exception comes back to you there's no point in doing anything with it other than logging it. The Swing event queue has basically that type of behavior.

Alternatively, you could provide a hook for an "uncaught exception handler," similar to ThreadGroup. Be aware that the handler could take a long time, and end up delaying your dispatcher.

As far as InterruptedException goes: the only thing that cares about that is your dispatch loop, which should be checking some external state to see if it should stop processing.



来源:https://stackoverflow.com/questions/1097503/best-practices-for-catching-throwable-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!