在Java中捕获Throwable的最佳做法 [英] Best practices for catching Throwable in Java
问题描述
我可以想到的一个最佳做法是总是重新抛出异常,如果它是InterruptedException,因为这意味着有人中断了我的线程并想要杀死它。
另一个建议(来自评论,而不是答案)是始终重新推荐 可能最重要的一个是,永远不会吞噬被检查的异常。这个意思是不要这样做: 除非这是你打算 。有时候,人们会检查异常,因为他们不知道该怎么办,或者不想(或不能)用throws Exception子句污染他们的界面。 如果您不知道该怎么做,请执行以下操作: 另一个令人想到的是确保处理异常。读取文件应如下所示: 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: 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: The other one that springs to mind is to make sure you deal with exceptions. Reading a file should look something like this:
这篇关于在Java中捕获Throwable的最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
try {
...
} catch IOException e){
}
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){/ *吞下这一个* /}
}
try {
...
} catch (IOException e) {
}
try {
...
} catch (IOException e) {
throw new RuntimeException(e);
}
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 */ }
}