自定義一個類繼承Exception,調用父類的有參構造,父類的有參構造會幫我們在控制檯輸出錯誤信息
package com.itzhengmax.test08;
public class MyException extends Exception {
public MyException() {
super("性別錯誤");
}
}
自定義一個測試代碼,手動拋出異常
package com.itzhengmax.test08;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("請輸入性別");
String sex = sc.next();
if (!(sex.equals("男") || sex.equals("女"))) {
try {
throw new MyException();
} catch (MyException e) {
// TODO: handle exception
e.printStackTrace();
System.out.println("設置默認性別爲男");
sex = "男";
}
}
System.out.println(sex);
}
}
測試結果