第43条:抛出的异常要适合于相应的抽象
高层的实现,应该捕获低层的异常,同时抛出一个可以按照高层抽象进行解释的异常,这种做法叫做异常转译(exception translation)。即如:
//exception translation!
try{
//use lowlevel abstraction to do our bidding
...
}catch(LowerLevelException e){
throw new HigherLevelException(...);
}
低层的异常被高层的异常保存起来,且高层的异常提供一个公有的访问方法来获得低层的异常,这种做叫做异常链接(exception chaining)。
//Exception chaining.
try{
//use lower-level abstraction to do our bindding
...
}catch(LowerLevelException e){
throw new HigherLevelException(e);
}
异常链的实现非常简单,在1.4及以后版本中,可以通过Throwable来获得支持。
//Exception chaining in release 1.4 or later
HigherLevelException(Throwable t){
super(t);
}
如果是在早期java版本中,则需要先将其保存:
//Exception chaining prior to release 1.4
private Throwable cause;
HigherLevelException(Throwable t){
cause=t;
}
public Throwable getCause(){
return cause;
}
处理来自低层的异常,
联系客服