rip*_*234 12 java exception throwable
有时,您只需要捕获Throwable,例如在编写调度程序队列时调度通用项目并需要从任何错误中恢复(所述调度程序记录所有捕获的异常,但是静默,然后继续执行其他项目).
我能想到的一个最佳实践是,如果它是InterruptedException,则总是重新抛出异常,因为这意味着有人打断了我的线程并想要杀死它.
另一个建议(来自评论,而不是答案)是始终重新抛出ThreadDeath
还有其他最佳做法吗?
cle*_*tus 12
可能最重要的是,永远不要吞下一个经过检查的例外.我的意思是不要这样做:
try {
...
} catch (IOException e) {
}
Run Code Online (Sandbox Code Playgroud)
除非那是你想要的.有时人们会吞下已检查的异常,因为他们不知道如何使用它们,或者不想(或不能)使用"抛出异常"子句来污染它们的界面.
如果您不知道如何处理它,请执行以下操作:
try {
...
} catch (IOException e) {
throw new RuntimeException(e);
}
Run Code Online (Sandbox Code Playgroud)
想到的另一个是确保你处理异常.读取文件应该如下所示:
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 */ }
}
Run Code Online (Sandbox Code Playgroud)