java_自定義異常

自定義異常格式:

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();
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章