在Java編程中,如何創建用戶自定義異常?
此示例顯示如何通過擴展Exception
類來創建用戶定義的異常。
package com.zaixian;
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