虽然我同意捕获原始异常并不是一种好的方式,但是有一些方法可以处理异常,这些异常提供了卓越的日志记录以及处理意外情况的能力。 由于您处于异常状态,因此您可能对获取良好信息比对响应时间更感兴趣,因此性能的实例不应该是一个大问题。
try{
// IO code
} catch (Exception e){
if(e instanceof IOException){
// handle this exception type
} else if (e instanceof AnotherExceptionType){
//handle this one
} else {
// We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy.
throw e;
}
}
但是,这并没有考虑到IO也可以抛出错误的事实。 错误不是例外。 错误是与异常不同的继承层次结构,尽管它们共享基类Throwable。 由于IO可以抛出错误,你可能想要抓住Throwable
try{
// IO code
} catch (Throwable t){
if(t instanceof Exception){
if(t instanceof IOException){
// handle this exception type
} else if (t instanceof AnotherExceptionType){
//handle this one
} else {
// We didn't expect this Exception. What could it be? Let's log it, and let it bubble up the hierarchy.
}
} else if (t instanceof Error){
if(t instanceof IOError){
// handle this Error
} else if (t instanceof AnotherError){
//handle different Error
} else {
// We didn't expect this Error. What could it be? Let's log it, and let it bubble up the hierarchy.
}
} else {
// This should never be reached, unless you have subclassed Throwable for your own purposes.
throw t;
}
}