自定义异常运行实例
/* 自定义异常:ScoreException */ public class ScoreException extends Exception { //无参构造 public ScoreException(){} //带参构造 public ScoreException(String message){ super(message); } }
/* 定义教师类 */ public class Teacher { public void checkScore(int score) throws Exception{ if (score < 0 || score > 100){ throw new ScoreException("你输入的分数有误"); }else { System.out.println("分数正常"); } } }
/* 测试类 */ import java.util.Scanner; 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(); try { t.checkScore(score); } catch (Exception e) { e.printStackTrace(); } } }
当输入的成绩不在正常的范围内时,会输出异常提醒
请输入分数:
120
com.itheima_02.ScoreException: 你输入的分数有误
at com.itheima_02.Teacher.checkScore(Teacher.java:6)
at com.itheima_02.TeacherTest.main(TeacherTest.java:13)
学习的博客多用于在笔记中,防止笔记过于臃肿,所以将样例及运行结果放在博客中,后以超链接的形式记录在笔记中,所以有些博文过于单薄。如果有小伙伴遇到问题欢迎评论,看到就会回复,学渣一枚,加油努力。