示範繼承 Exception 建立自訂異常 MyException,提供三種建構子(無參、訊息、訊息+錯誤碼),並在 main 中透過 try-catch 捕獲展示 getMessage()、toString()、printStackTrace()、自訂 val() 取錯誤碼。
class MyException extends Exception {
private int i;
public MyException() {}
public MyException(String msg) { super(msg); }
public MyException(String msg, int x) { super(msg); i = x; }
public int val() { return i; }
}
public class DemoException {
public static void a() throws MyException { throw new MyException(); }
public static void b() throws MyException { throw new MyException("Originated in b()"); }
public static void c() throws MyException { throw new MyException("Originated in c()", 47); }
public static void main(String[] args) {
try { a(); } catch (MyException e) { e.getMessage(); }
try { b(); } catch (MyException e) { e.toString(); }
try { c(); } catch (MyException e) {
e.printStackTrace();
System.out.println("error code: " + e.val());
}
}
}
Exception(受檢異常)或 RuntimeException(非受檢)。super(msg) 保留錯誤訊息。i)並提供存取方法。printStackTrace() 輸出完整堆疊軌跡,除錯首選。