package prac_1;
/**
* <p>Title: 捕獲異常和實現自己的異常類</p>
* <p>Description: 通過繼承Exception類來實現自己的異常類。並使用try-catch來捕獲這個異常。</p>
* <p>Copyright: Copyright (c) 2014</p>
* <p>Filename: </p>
* @author 王海濤
* @version 0.1
*/
class MyException extends Exception {
public MyException() {}
public MyException(String msg) {
super(msg);
}
public MyException(String msg, int x) {
super(msg);
i = x;
}
public int val() { return i; }
private int i;
}
public class ExceptionDemo {
/**
*<br>方法說明:使用MyException類中默認的構造器
*/
public static void a() throws MyException {
System.out.println(
"Throwing MyException from a()");
throw new MyException();//拋出異常,結束方法
}
/**
*<br>方法說明:使用MyException類中帶信息的構造器
*/
public static void b() throws MyException {
System.out.println(
"Throwing MyException from b()");
throw new MyException("error in b ()");
}
/**
*<br>方法說明:使用了MyException中有編碼的構造器
*/
public static void c() throws MyException {
System.out.println(
"Throwing MyException from c()");
throw new MyException(
"error in c()", 404);
}
public static void main(String[] args) {
try {
a();
} catch(MyException e) {
System.out.println( "Error="+e.getMessage());
}
try {
b();
} catch(MyException e) {
System.out.println( "Error="+e.getMessage());
//e.toString();
}
try {
c();
} catch(MyException e) {
System.out.println( "Error="+e.getMessage());
e.printStackTrace();
System.out.println("error code: " + e.val());
}
}
} //end :)
每天一點兒java---繼承exception類來實現自己的異常類
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.