在Java程式設計中,如何建立使用者自定義異常?
此範例顯示如何通過擴充套件Exception
類來建立使用者定義的異常。
package com.yiibai;
class MyException extends Exception {
String s1;
MyException(String s2) {
s1 = s2;
}
@Override
public String toString() {
return ("Output String = " + s1);
}
}
public class UserDefinedException {
public static void main(String args[]) {
try {
throw new MyException("Custom message");
} catch (MyException exp) {
System.out.println(exp);
}
}
}
上述程式碼範例將產生以下結果 -
Output String = Custom message