Geo*_*Geo 8 java coding-style exception
在一个方法中进行多次尝试并构造这样的代码是不是被认为是不好的做法?
public void whatever() {
try {
methodThatMayThrowIOException();
} catch(IOException io) {
// do something with exception here
}
// do more stuff here that won't throw exceptions
try {
methodThatMayThrowCustomException();
} catch(CustomException ce) {
// do something with custom exception here
}
}
Run Code Online (Sandbox Code Playgroud)
不,这不对.当它们被抛出时捕获特定异常是一个很好的观点,它肯定比这更好:
public void whatever {
try {
methodThatMayThrowIOException();
// do more stuff here that won't throw exceptions
methodThatMayThrowCustomException();
} catch(ParentException e) {
// do something with custom exception here
}
}
Run Code Online (Sandbox Code Playgroud)
您的代码读起来就像它一样,因为您想要执行第 1 部分(并解析,IOException必要时进行捕获),执行无异常部分,然后执行methodThatMayThrowCustomException. 您的代码实际上无法以任何其他方式编写并保留相同的功能。这是夸张的说法,但任何其他版本在表面意义上都会有所不同。
这不一样:
public void whatever {
try {
methodThatMayThrowIOException();
// do more stuff here that won't throw exceptions
methodThatMayThrowCustomException();
} catch(IOException io) {
// do something with io exception here
} catch(CustomException ce) {
// do something with custom exception here
}
}
Run Code Online (Sandbox Code Playgroud)
如果抛出任何异常,它的执行方式也完全不同。如果您需要按顺序从第 1 部分恢复,无论如何都要点击第 2 部分,然后继续第 3 部分,您实际上无法以任何其他方式编写代码。
使用两个 catch 块并没有什么问题,但将导致 IOException 的内容与引发 CustomException 的内容混合在一起可能会导致问题混合,从而使代码难以理解。但事实上,它不仅有效,而且是做你正在做的事情的唯一方法。