Java 實例 - 自定義異常
以下實例演示了通過繼承 Exception 來實現自定義異常:
TestInput.java 檔
class WrongInputException extends Exception { // 自定義的類
WrongInputException(String s) {
super(s);
}
}
class Input {
void method() throws WrongInputException {
throw new WrongInputException("Wrong input"); // 拋出自定義的類
}
}
class TestInput {
public static void main(String[] args){
try {
new Input().method();
}
catch(WrongInputException wie) {
System.out.println(wie.getMessage());
}
}
}
以上代碼運行輸出結果為:
Wrong input