在当前的Java项目中,我们有类似于以下示例的代码:
try {
doSomeThing(anObject);
}
catch (SameException e) {
// Do nothing or log, but don't abort current method.
}
try {
doOtherThing(anObject);
}
catch (SameException e) {
// Do nothing or log, but don't abort current method.
}
// ... some more calls to different method ...
try {
finallyDoYetSomethingCompletelyDifferent(anObject);
}
catch (SameException e) {
// Do nothing or log, but don't abort current method.
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,使用完全相同的对象调用了几个不同的方法,并且对于每个调用,捕获并处理相同的异常(或以非常类似的方式).异常不会被重新抛出,但可能只会被记录然后被丢弃.
try-catch围绕每个方法存在的唯一原因是始终执行所有方法,无论先前执行的方法是否失败.
我根本不喜欢上面的代码.它占用了大量的空间,非常重复(尤其是在catch-block中完成的日志记录;此处未提供)并且看起来很糟糕.
我可以想到其他一些编写代码的方法,但是也不太喜欢它们.我想到了以下选项:
循环切换顺序/用于案例范例