自定义异常ScoreException

package myScoreException;

public class ScoreException extends Exception {
          
   

    public ScoreException() {
          
   }

    public ScoreException(String message) {
          
   
        super(message);
    }
}
package myScoreException;

public class Teacher {
          
   
    public void checkScore(int score) throws ScoreException {
          
   
        if (score < 0 || score > 100) {
          
   
            throw new ScoreException("分数有误,应在0-100之间");
        }
        else {
          
   
            System.out.println("分数正常");
        }
    }
}
package myScoreException;

import java.util.Scanner;

public class TeacherTest {
          
   
    public static void main(String[] args) {
          
   
        Scanner sc = new Scanner(System.in);
        int score = sc.nextInt();

        Teacher t = new Teacher();
        try {
          
   
            t.checkScore(score);
        } catch (ScoreException e) {
          
   
            e.printStackTrace();
        }
    }
}
经验分享 程序员 微信小程序 职场和发展