我們可以創(chuàng)建我們自己的異常類(lèi)。
它們必須擴(kuò)展現(xiàn)有的異常類(lèi)。
<Class Modifiers> class <Class Name> extends <Exception Class Name> { }
<Class Name> is the exception class name.
創(chuàng)建一個(gè)MyException類(lèi),它擴(kuò)展了java.lang.Exception類(lèi)。
語(yǔ)法如下:
public class MyException extends Exception { }
異常類(lèi)與Java中的任何其他類(lèi)一樣。通常,我們不向我們的異常類(lèi)中添加任何方法。
許多有用的方法可以用來(lái)查詢(xún)異常對(duì)象的狀態(tài)在Throwable類(lèi)中聲明。
通常,我們?yōu)槲覀兊漠惓n?lèi)包括四個(gè)構(gòu)造函數(shù)。
所有構(gòu)造函數(shù)將使用super關(guān)鍵字調(diào)用其超類(lèi)的相應(yīng)構(gòu)造函數(shù)。
class MyException extends Exception { public MyException() { super(); } public MyException(String message) { super(message); } public MyException(String message, Throwable cause) { super(message, cause); } public MyException(Throwable cause) { super(cause); } }
第一個(gè)構(gòu)造函數(shù)創(chuàng)建一個(gè)具有null的異常作為其詳細(xì)消息。
第二個(gè)構(gòu)造函數(shù)創(chuàng)建一個(gè)具有詳細(xì)消息的異常。
第三和第四個(gè)構(gòu)造函數(shù)允許您通過(guò)包裝/不包含詳細(xì)消息的另一個(gè)異常來(lái)創(chuàng)建異常。
您可以拋出類(lèi)型MyException的異常。
throw new MyException("Your message goes here");
我們可以在方法/構(gòu)造函數(shù)聲明中的throws子句中使用MyException類(lèi),或者在catch塊中使用參數(shù)類(lèi)型。
public void m1() throws MyException { }
或捕獲異常類(lèi)
try { }catch(MyException e) { }
下面的列表顯示了Throwable類(lèi)的一些常用方法。
Throwable類(lèi)是Java中所有異常類(lèi)的超類(lèi)。此表中顯示的所有方法在所有異常類(lèi)中都可用。
以下代碼演示了對(duì)異常類(lèi)使用printStackTrace()方法。
public class Main { public static void main(String[] args) { try { m1(); } catch (MyException e) { e.printStackTrace(); // Print the stack trace } } public static void m1() throws MyException { m2(); } public static void m2() throws MyException { throw new MyException("Some error has occurred."); } } class MyException extends Exception { public MyException() { super(); } public MyException(String message) { super(message); } public MyException(String message, Throwable cause) { super(message, cause); } public MyException(Throwable cause) { super(cause); } }
上面的代碼生成以下結(jié)果。
以下代碼顯示了如何將異常的堆棧跟蹤寫(xiě)入字符串。
import java.io.PrintWriter; import java.io.StringWriter; public class Main { public static void main(String[] args) { try { m1(); } catch (MyException e) { String str = getStackTrace(e); System.out.println(str); } } public static void m1() throws MyException { m2(); } public static void m2() throws MyException { throw new MyException("Some error has occurred."); } public static String getStackTrace(Throwable e) { StringWriter strWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(strWriter); e.printStackTrace(printWriter); // Get the stack trace as a string String str = strWriter.toString(); return str; } } class MyException extends Exception { public MyException() { super(); } public MyException(String message) { super(message); } public MyException(String message, Throwable cause) { super(message, cause); } public MyException(Throwable cause) { super(cause); } }
上面的代碼生成以下結(jié)果。
更多建議: