这是在
Java 6上
我可以有一个通用的方法来处理我的异常 – 所以不要在每个方法中执行n次
try {
// Do something
} catch (XException e) {
// Do something
} catch (YException e) {
// Do something
} catch (ZException e) {
// Do something
}
我有
try {
// Do something
} catch (Exception e) {
handleAll (e);
}
和方法handleAll(e)
if e.instanceOf(XException)
else if e.instanceOf(YException)
else if e.instanceOf(ZException)
第二种方法有什么问题吗?
更新:
我最初的问题是关于“集中处理”在一个地方对于检查和运行时异常.答案指出我应该避免使用instanceof().
@ aioobe的想法看起来很整洁.对这种方法有任何负面意见吗?