【正文】
lic成員方法 成員方法 描述 getMessage() 返回當(dāng)前異常的描述性信息,其中主要包括異常類的名稱及有關(guān)異常的簡(jiǎn)短描述。 printStackTrace() 將堆棧的跟蹤信息輸出到標(biāo)準(zhǔn)的輸出流中。在控制臺(tái)方式下 ,標(biāo)準(zhǔn)輸出流指屏幕。 printStackTrack(PrintStream s) 將堆棧的跟蹤信息通過參數(shù) s返回。 fillInstackTrack() 填寫跟蹤信息。 定義異常類 除了異常類必須是 Throwable類的子類之外,建 議最好將定義的異常類作為 Exception的子類,這 樣 Java編譯器才能跟蹤程序中拋出的異常位置。 定義異常類的基本格式: class TestException extends Exception { TestException(){super()。} TestException(String s){ super(s)。} } 應(yīng)用自定義的異常類 //filename: public class Test { public static void main(String[] args) { for (int i=0。i。i++) { try { thrower(args[i])。 (Test\+args[i]+\ didn39。t throw an exception)。 } catch(Exception e){ (Test\+args[i]+\ threw a +()+\n with message:+())。 } } } static int thrower(String s) throws TestException { try { if ((divide)){ int i=0。 return i/i。 } if ((null)) { s=null。 return ()。 } if ((test)) throw new TestException(Test message)。 } finally{ ([thrower(\+s+\)done])。 } } }//end of class Test [thrower(divide)done] Testdivide threw a class with message:/ by zero [thrower(null)done] Testnull threw a classs with message:null [thrower(not)done] Testnot didn39。t throw an exception [thrower(test)done] Testtest threw a class TestException with message:Test message 運(yùn)行這個(gè)程序后,應(yīng)該得下面所示的結(jié)果: