並不一定非要使用Java違例
為創建自己的違例類
//: Inheriting
// Inheriting your own exceptions
class MyException extends Exception {
public MyException() {}
public MyException(String msg) {
super(msg);
}
}
public class Inheriting {
public static void f() throws MyException {
System
throw new MyException();
}
public static void g() throws MyException {
System
throw new MyException(
}
public static void main(String[] args) {
try {
f();
} catch(MyException e) {
e
}
try {
g();
} catch(MyException e) {
e
}
}
} ///:~
繼承在創建新類時發生
class MyException extends Exception {
public MyException() {}
public MyException(String msg) {
super(msg);
}
}
這裡的關鍵是
該程序輸出結果如下
Throwing MyException from f()
MyException
at Inheriting
at Inheriting
Throwing MyException from g()
MyException: Originated in g()
at Inheriting
at Inheriting
可以看到
創建自己的違例時
//: Inheriting
// Inheriting your own exceptions
class MyException
public MyException
public MyException
super(msg);
}
public MyException
super(msg);
i = x;
}
public int val() { return i; }
private int i;
}
public class Inheriting
public static void f() throws MyException
System
throw new MyException
}
public static void g() throws MyException
System
throw new MyException
}
public static void h() throws MyException
System
throw new MyException
}
public static void main(String[] args) {
try {
f();
} catch(MyException
e
}
try {
g();
} catch(MyException
e
}
try {
h();
} catch(MyException
e
System
}
}
} ///:~
此時添加了一個數據成員i
Throwing MyException
MyException
at Inheriting
at Inheriting
Throwing MyException
MyException
at Inheriting
at Inheriting
Throwing MyException
MyException
at Inheriting
at Inheriting
e
由於違例不過是另一種形式的對象
//: SimpleException
class SimpleException extends Exception {
} ///:~
它要依賴編譯器來創建默認構建器(會自動調用基礎類的默認構建器)
From:http://tw.wingwit.com/Article/program/Java/JSP/201311/19485.html