天天看點

自定義異常,實作異常鍊的功能

自定義異常,實作異常鍊的功能

1.package com.min;

public class DrunkException extends Exception{

public DrunkException(){

}

public DrunkException(String message){
    super(message);
}
           

}

2.

package com.min;

public class ChainTest {

public static void main(String[] args) {
    ChainTest ct=new ChainTest();
    try{ct.test2();
    }catch(Exception e){
        e.printStackTrace();
    }
}

public void test1() throws DrunkException{
    throw new DrunkException("喝酒别開車!!!");
}

public void test2(){
    try{
        test1();
    }catch(DrunkException e){
        RuntimeException newExc=new RuntimeException("司機一滴酒,親人兩行淚");
        newExc.initCause(e);
        throw newExc;
    }
}
           

}

java.lang.RuntimeException: 司機一滴酒,親人兩行淚

at com.min.ChainTest.test2(ChainTest.java:21)

at com.min.ChainTest.main(ChainTest.java:7)

Caused by: com.min.DrunkException: 喝酒别開車!!!

at com.min.ChainTest.test1(ChainTest.java:14)

at com.min.ChainTest.test2(ChainTest.java:19)

… 1 more