格式:
public class 异常类名 extends Exception{
无参构造
有参构造
}
应用:测试老师输入的分数是否有误
ScoreException.java
public class ScoreException extends Exception {
public ScoreException() {}
public ScoreException(String message) {
super(message);
}
}
Teacher.java
public class Teacher {
public void checkScore(int score) throws ScoreException {
if(score<0 || score>100) {
// throw new ScoreException();
throw new ScoreException("分数有误,范围在0-100之间");
} else {
System.out.println("成绩正常");
}
}
}
测试类
Demo.java
public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入分数:");
int score = sc.nextInt();
Teacher t = new Teacher();
try {
t.checkScore(score);
} catch (ScoreException e) {
e.printStackTrace();
}
}
}