自定義異常格式:
public class 異常類名 extends Exception {
無參構造
帶參構造
}
實例:
首先自定義一個分數異常類 ScoreException
public class ScoreException extends Exception {
public ScoreException() { }
public ScoreException(String message) {
super(message);
}
}
然後創建一個Teacher類 繼承 ScoreException類
public class Teacher {
public void checkScore(int score) throws ScoreException {
if(score>=0&&score<=100) {
System.out.println("分數正常");
}else{
// throw new ScoreException(); //
throw new ScoreException("分數輸入有誤,應在0-100之間!");
}
}
}
然後驗證自定義異常是否正確
public class TeacherTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("請輸入分數: ");
int score = sc.nextInt();
Teacher t = new Teacher();
// t.checkScore(score); // Alt + Enter 選擇 try/catch 選項
try {
t.checkScore(score);
} catch (ScoreException e) {
e.printStackTrace();
}
}
}