寫DrunkException的時候出現了一個問題:類型 serializable 類 DrunkException 未聲明類型為 long 的靜態終態 serialVersionUID 字段
這個代碼有錯:
package imooc.exception.test;
public class DrunkException extends Exception {
public DrunkException() {}
public DrunkException(String message) {
super(message);
}
}
那個類那邊提示類型 serializable 類 DrunkException 未聲明類型為 long 的靜態終態 serialVersionUID 字段,這是什么意思呀?
下面是ChainTest類,看看有沒有錯:
package imooc.exception.test;
public class ChainTest {
/*
* 這個類完成的工作:第一個方法(Test1):拋出“喝大了”異常;
* 第二個方法(Test2):調用Test1,捕獲“喝大了”異常,并包裝成運行時異常,繼續拋出;
* main方法中調用test2,嘗試捕獲test2方法拋出的異常
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ChainTest ct = new ChainTest();
try {
ct.test2();
}catch(Exception e) {
e.getStackTrace();
}
}
public void test1() throws DrunkException {
throw new DrunkException("喝車別開酒!");
}
public void test2() {?
try {
test1();
} catch (DrunkException e) {
// TODO 自動生成的 catch 塊
//e.printStackTrace();這個就不需要了
RuntimeException newExc = new RuntimeException("司機一滴酒,親人兩行淚");//新建一個RuntimeException,起名叫newExc
newExc.initCause(e);//調用newExc的initCause方法并把捕獲的DrunkException放進去
throw newExc;//拋出新異常
}
}
}
2019-08-27