來源:北大青鳥飛迅校區(qū)|發(fā)布時間:2013-04-21 19:10:38
基礎(chǔ)編程中自定義Java異常:
1.前言:
你的程序總有一天會崩潰掉,在崩潰掉的時候我們要知道它在哪,為了什么而崩潰掉,數(shù)據(jù)的保存或者丟失情況如何等問題。我們可以通過繼承類java.lang.Throwable的子類:Exception來設(shè)計我們自己的Java異常。Exception類用于描述程序能夠捕獲的異常,如ClassNotFoundException。要注意的是自定義異常類之間也可以有繼承關(guān)系,同時也需要為自定義異常類設(shè)計構(gòu)造方法,以方便構(gòu)造自定義異常對象。
2.設(shè)計實例分析:
這是個比較完整的自定義異常類的設(shè)計,其實是比較模板化的東西。
package playground;
import java.io.*;
public class MyException extends Exception {
private int id; // a unique id
private String classname; // the name of the class
private String method; // the name of the method
private String message; // a detailed message
private MyException previous =
null; // the exception which was caught
private String separator = "n"; // line separator
public MyException(int id, String classname, String method,
String message, MyException previous) {
this.id = id;
this.classname = classname;
this.method = method;
this.message = message;
this.previous = previous;
}
public String traceBack() {
return traceBack("n");
}
public String traceBack(String sep) {
this.separator = sep;
int level = 0;
MyException e = this;
String text = line("Calling sequence (top to bottom)");
while (e != null) {
level++;
text += line("--level " + level + "--------------------------------------");
text += line("Class/Method: " + e.classname + "/" + e.method);
text += line("Id : " + e.id);
text += line("Message : " + e.message);
e = e.previous;
}
return text;
}
private String line(String s) {
return s + separator;
}
}
我們來一個個看看這些東西:
在這個繼承了Exception類的自定義異常類中,我們定義了如下變量:
id:獨立標(biāo)示符,這個是用來進行標(biāo)示類中什么地方出現(xiàn)了錯誤被捕捉到。
classname:捕捉到這個錯誤的類的名字。
全程面授,不高薪都難
申請成功后,我們將在24小時內(nèi)與您聯(lián)系
招生熱線: 4008-0731-86 / 0731-82186801
學(xué)校地址: 長沙市天心區(qū)團結(jié)路6號
Copyright © 2006 | 湖南大計信息科技有限公司 版權(quán)所有
湘ICP備14017520號-3