JavaSE-13.3.5【throws和throw的区别、自定义异常】

 

 

 1 package day4.haifei03;
 2 
 3 /*
 4 3.7 自定义异常
 5     public class 自定义异常类名 extends Exception {
 6         无参构造
 7         有参构造
 8     }
 9 
10 3.8 throws和throw的区别
11  */
12 public class ScoreException extends Exception{
13 
14     public ScoreException(){}
15 
16     public ScoreException(String message){
17         super(message); //将message传给父类
18     }
19 
20 }
 1 package day4.haifei03;
 2 
 3 public class Teacher {
 4 
 5     public void checkScore(int score) throws ScoreException{
 6         if(score<0 || score>100){
 7             //注意是throw;记得要方法名处要throws ScoreException,不然红色波浪线警告
 8 //            throw new ScoreException(); //无参构造
 9             throw new ScoreException("输入分数有误"); //有参构造
10         }else {
11             System.out.println("分数正常");
12         }
13     }
14 
15 }
 1 package day4.haifei03;
 2 
 3 import java.util.Scanner;
 4 
 5 public class TeacherDemo {
 6     public static void main(String[] args) {
 7         Scanner sc = new Scanner(System.in);
 8         System.out.println("请输入分数:");
 9         int score = sc.nextInt();
10 
11         Teacher t = new Teacher();
12         try {
13             t.checkScore(score); //编译时异常 try-catch显示处理
14         } catch (ScoreException e) {
15             e.printStackTrace();
16         }
17 
18         /*请输入分数:
19         222
20         day4.haifei03.ScoreException
21         at day4.haifei03.Teacher.checkScore(Teacher.java:7)
22         at day4.haifei03.TeacherDemo.main(TeacherDemo.java:13)*/
23 
24         /*请输入分数:
25         -44
26         day4.haifei03.ScoreException: 输入分数有误
27         at day4.haifei03.Teacher.checkScore(Teacher.java:9)
28         at day4.haifei03.TeacherDemo.main(TeacherDemo.java:13)*/
29     }
30 }

 

posted @ 2021-05-29 16:17  yub4by  阅读(51)  评论(0编辑  收藏  举报