Java try-catch自定义捕捉异常

  题目要求:输入数值,90-100输出“优”,80-90输出“良”,70-80输出“中”,60-70输出“及格”,0-60输出“不及格”,输入其他捕捉异常并提示相应信息。

  代码如下:

 1 import java.util.Scanner;
 2 
 3 @SuppressWarnings("serial")
 4 //自定义异常类
 5 class TryException extends Exception
 6 {
 7     /**
 8      * 
 9      */
10     private static final long serialVersionUID = 1L;
11     public TryException(String Message) {
12         super(Message);
13     }
14 }
15 
16 public class TryTheWrong {
17     static Scanner in = new Scanner(System.in);
18     public static void main(String args[]) {
19         //运行try-catch
20         try {
21             JudgeError();
22         }
23         catch(TryException e) {
24             //输出自定义异常中的信息
25             System.out.println( e.getMessage() );
26         }
27     }
28     //运行方法,包括输入值,对值的判断以及将要反馈的异常信息throw给自定义异常类
29     public static void JudgeError() throws TryException
30     {
31         String s=in.next();
32         String m="^[0-9]*$";
33         //判定是否全为数字
34         if(!s.matches(m)) {
35             throw new TryException("输入含非数字项");
36         }
37         //string转int
38         int i = Integer.valueOf(s);
39         if(i>100) {
40             throw new TryException("输入数值小于0或大于100");
41         }
42         if(i>=90&&i<=100) {
43             System.out.println("优");
44         }
45         else if(i>=80&&i<90) {
46             System.out.println("良");
47         }
48         else if(i>=70&&i<80) {
49             System.out.println("中");
50         }
51         else if(i>=60&&i<70) {
52             System.out.println("及格");
53         }
54         else if(i>=0&&i<60) {
55             System.out.println("不及格");
56         }
57         else {
58             System.out.println("ERROR");
59         }
60     }
61 }

  创建自定义异常类TryException,利用super()和throw new捕捉反馈的异常信息,最后通过catch中System.out.println(e.getMessage());输出。注意在实行该操作时,类(JudgeError)要throws对应的类名(TryException)。由于输入未知,可能含有非数字元素,因此在进行输入操作时,先作为字符串输入,通过正则表达式判定是否都为数字,再将string转化为int,判断其是否大于100,根据结果判断是否反馈异常信息,若都没有问题,则继续执行下面的if-else if操作,输出正确结果。