我们都会不时编写这样的代码:
try {
// ... some code.
} catch (SomeException e) {
// ... No action is required, just ignore.
}
Run Code Online (Sandbox Code Playgroud)
有没有像注释这样的标准代码片段来表明我们真的打算忽略异常?向其他团队成员和静态分析器展示的东西我们真的需要像InterruptedException以后一样跳过这种情况Thread.sleep()吗?就像是:
Exception.ignore(e);
Run Code Online (Sandbox Code Playgroud)
谷歌搜索但没有找到这种情况的标准.
这与确保例外的测试特别相关:
try {
action();
fail("We expected this to fail.");
} catch (ExpectedException e) {
ignore(e, "OK, so far so good.");
}
Run Code Online (Sandbox Code Playgroud)
忽略异常的唯一方法是捕获并吞下它,当然,对于异常非常具体,您不想捕获Exception e,那将是一个非常糟糕的主意。
try{
... //code
}
catch( VerySpecificException ignore){
Log(ignore);
}
Run Code Online (Sandbox Code Playgroud)
日志记录显然是可选的,但却是一个很好的做法。