Java基础:异常的限制

 1 package cn.tju.thinkinginjava.exception;
 2 
 3 @SuppressWarnings("serial")
 4 class BaseballException extends Exception {}
 5 @SuppressWarnings("serial")
 6 class Foul extends BaseballException {}
 7 @SuppressWarnings("serial")
 8 class Strike extends BaseballException {}
 9 @SuppressWarnings("serial")
10 class PopFoul extends Foul {}
11 @SuppressWarnings("serial")
12 class StormException extends Exception {}
13 @SuppressWarnings("serial")
14 class RainedOut extends StormException {}
15 
16 abstract class Inning {
17     /**
18      * 说明异常,但可以不抛出
19      */
20     public Inning() throws BaseballException {}
21     
22     public void event() throws BaseballException {}
23     
24     public abstract void atBat() throws Strike, Foul;
25     
26     public void walk() {}
27 }
28 interface Storm {
29     public void event() throws RainedOut;
30     public void rainHard() throws RainedOut;
31 }
32 
33 public class StormyInning extends Inning implements Storm {    
34     /**
35      * 1、可以向子类构造器中加入新的异常说明,但是必须声明基类构造器的异常
36      * */
37     public StormyInning() throws RainedOut, BaseballException {}
38     public StormyInning(String s) throws Foul, BaseballException {}
39 
40     /**
41      * 2、普通方法的异常说明必须与基类方法一致,或少于基类方法;对接口也一样
42      * */ 
43     //!public void walk() throws PopFoul {} // Compile error
44     public void rainHard() throws RainedOut {}
45     
46     /**
47      * 3、接口不能为基类中存在的方法扩展其异常说明,同样基类也不能为在接口中声明的方法扩展其异常说明。
48      * 某方法同时存在于基类和接口中,这种情况下,只能减少该方法的异常说明。
49      * */
50     public void event(){}
51     /**
52      * 4、重写的方法,其异常说明中的异常类
53      * 可以是
54      * 其基类方法的异常
55      * 的
56      * 子类
57      * */
58     public void atBat() throws PopFoul {}
59 
60     public static void main(String[] args) {
61         Inning in = null;
62         try {
63              in = new StormyInning();
64         } catch (RainedOut e) {            
65             e.printStackTrace();
66         } catch (BaseballException e) {            
67             e.printStackTrace();
68         }        
69         //注意这里,需捕获Inning.atBat()抛出的异常
70         try {
71             in.atBat();
72         } catch (Strike e) {            
73             e.printStackTrace();
74         } catch (Foul e) {
75             e.printStackTrace();
76         }
77 
78         /*----------------------------------------------------------------*/
79         StormyInning sin = null;
80         try {
81             sin = new StormyInning();
82         } catch (RainedOut e) {            
83             e.printStackTrace();
84         } catch (BaseballException e) {            
85             e.printStackTrace();
86         }
87         
88         //注意这里,需捕获StormyInning.atBat()抛出的异常
89         try {
90             sin.atBat();
91         } catch (PopFoul e) {
92             e.printStackTrace();
93         }
94     }
95 }
原文地址:https://www.cnblogs.com/QuentinYo/p/3659467.html