package com; import java.util.Scanner; public class ScoreException extends Exception{ public ScoreException(){ } public ScoreException(String message){ super(message); } } package com; public class Teacher { public void check(int score) throws ScoreException{ if(score < 0 || score >100){ throw new ScoreException("你给的分数有误!"); }else{ System.out.println("输入正确"); } } } package com; import java.util.Scanner; public class TeacherTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int s = sc.nextInt(); Teacher t = new Teacher(); t.check(s);//因为定义的是编译时异常,所以必须使用以下异常处理语句, //若定义的异常类继承自RuntimeException即运行时异常,则可以不用下面语句。 // try { // t.check(s); // } catch (ScoreException e) { // e.printStackTrace(); // } } }