自定义异常

异常:如果不处理就抛出,最终系统就会处理,并终止程序。添加try catch ,异常出现后,异常后面的代码仍然可以继续得到执行。

 

自定义异常:先创建一个自定义异常类 extends Exception

1 public class SException extends Exception {
2     public SException() {
3         super();
4     }
5 
6     public SException(String string) {
7         super(string);
8     }
9 }

自定义异常类使用:

  1. 在方法头部 throws 异常
    1  static double divide() throws SException { }

     

  2. 在方法体中判断异常类型,添加自定义异常抛出
    1 if (num2 == 0) {
    2             throw new SException("不能为0");
    3         }

     

  3. 在使用类中处理异常
    1 try {
    2             System.out.println(divide());
    3         } catch (SException e) {
    4             // e.printStackTrace();
    5             System.out.println(e.getMessage());
    6         }

     

测试类:

 1 public class Test {
 2     /**
 3      * 异常:如果抛出,系统就会处理,并终止程序。添加try catch 异常出现后,后面的程序仍然可以继续运行。
 4      * 
 5      * @return
 6      */
 7     static double divide() throws SException { // 在方法头部先抛出异常
 8         Scanner scanner = new Scanner(System.in);
 9         System.out.println("input first num");
10         int num1 = 0;
11         int num2 = 0;
12         int d = 0;
13         try {
14             num1 = scanner.nextInt();
15             System.out.println("input second num");
16             num2 = scanner.nextInt();
17         } catch (Exception e) {
18             // e.printStackTrace();
19             System.out.println("输入不是数字!!");
20         }
21         scanner.close();
22         // 判断异常类型,添加自定义异常抛出
23         if (num2 == 0) {
24             throw new SException("不能为0");
25         }
26         d = num1 / num2;
27         System.out.println("异常后是否输出  in divide");
28         return d;
29     }
30 
31     public static void main(String[] args) {
32         // 自定义异常的处理
33         try {
34             System.out.println(divide());
35         } catch (SException e) {
36             // e.printStackTrace();
37            System.out.println(e.getMessage());
38         }
39         System.out.println("异常后是否输出  in mian");
40     }
41 
42 }

输出:

input first num
21
input second num
0
com.gam.test.SException: 不能为0
异常后是否输出  in mian
    at com.gam.test.Test.divide(Test.java:28)
    at com.gam.test.Test.main(Test.java:38)

 

try-catch-finally 语句体:

 1        void func() {
 2         try {
 3             //some Exception may happened
 4         } catch (MyException e) {
 5             func();
 6             return;
 7         } finally {
 8             //代码块1
 9         }
10         //代码块2
11     }

无异常发生时,catch内代码块不执行,有异常发生时,代码块1会执行,虽然在catch中有return,但finally代码块中的代码仍然会得到执行,只是代码块2中的代码不会得到执行。

 

posted @ 2015-07-30 11:45  pepelu  阅读(172)  评论(0编辑  收藏  举报