class CarWrongException extends Exception{
private static final long serialVersionUID = 1L;
public CarWrongException(String message, Throwable cause) {
super(message, cause);
}
public CarWrongException(String message) {
super(message);
}
}
class LateException extends Exception{
private static final long serialVersionUID = 1L;
public LateException(String message, Throwable cause) {
super(message, cause);
}
public LateException(String message) {
super(message);
}
}
class Car{
public void run() throws CarWrongException{
int a=2;
if(a==2) {
throw new CarWrongException("车,爆胎了");
}
System.out.println("开着车去上班");
}
}
class Worker{
private Car car=null;
Worker(Car car){
this.car=car;
}
public void gotowork() throws LateException{
try {
car.run();//正常开车去上班
System.out.println("开心");
}catch(CarWrongException e) {
e.printStackTrace(); //车抛锚了,出现异常
this.walk();
throw new LateException("迟到的原因:"+e.getMessage(),e);
}
}
private void walk() {
System.out.println("走路上班");
}
}
public class WhyDemo {
public static void main(String[] args) {
Car c=new Car();
Worker worker=new Worker(c);
try {
worker.gotowork();
System.out.println("老板给我奖金");
}catch(LateException e) {
System.out.println("打我");
e.printStackTrace();
}
}
}
异常转译:当位于最上层的子系统不需要关心底层的异常细节时,常见的做法就是捕获原始的异常,把它转换成为一个新的不同类型的异常,再抛出新的异常。
根据上述例子:我的车抛锚了,我在catch中重新抛出一个新的异常(LateException)给我的调用者老板,我们不能把车的异常信息抛给老板看,因为老板不关心这些细节,关心的是我迟到没。
异常链:把原始的异常包装为新的异常类,从而形成多个异常的有序排列,有助于查找产生异常的根本原因
异常链顾名思义就是将异常发生的原因一个传一个串起来,即把底层的异常信息传给上层,这样逐层抛出。Java API文档中给出了一个简单的模型: try { lowLevelOp(); } catch (LowLevelException le) { throw (HighLevelException) new HighLevelException().initCause(le); }