这通常不是关于异常处理的问题,但它特别适用于某些框架的使用.典型起点的几个例子:
> GWT:AsyncCallback接口的public void onFailure(Throwable caught)实现.
> JAX-RS:公共响应ExceptionMapper的响应(E throwable)实现< E extends Throwable>接口.
上述两种方法都接收Throwable的实例.通常,我看到开发人员使用一个简单的“if / else if”块来区分处理逻辑:
// As specified by the AsyncCallback class of the GWT framework
public void onFailure(Throwable caught) {
if (caught instanceof AnException) {
// handle AnException
} else if (caught instanceof AnotherException) {
// handle AnotherException
} else if (caught instanceof YetAnotherException) {
// handle YetAnotherException
} else if (caught instanceof ...) {
// and so on...
}
}
由于我不是“if / else if”块的粉丝,出于多种原因,我想出了以下“模式”,它将“if / else if”块转换为“try / catch”块,表现得好像它是一个“开关”块:
public void onFailure(Throwable caught) {
try {
throw caught;
} catch(AnException e1) {
// handle AnException
} catch(AnotherException e2) {
// handle AnotherException
} catch(YetAnotherException e3) {
// handle YetAnotherException
} catch(...) {
// and so on...
}
}
我的问题是:是否有任何缺点 – 在性能,最佳实践,代码可读性,一般安全性,或者我没有考虑或注意到的任何其他方面 – 使用这种方法?