如果异常具有继承体系,而我们的类也继承了某类且实现了接口,情况就复杂了
刚敲的例子:
- //定义一个异常的继承体系
- class BaseException extends Exception{}
- class StormException extends Exception{}
- class RainedOut extends StormException{}
- class AException extends BaseException{}
- class BException extends BaseException{}
- class UpperAException extends AException{}
- /* |AException--------|UpperAException
- * |BaseException--------|
- * Exception---------| |BException
- * |
- * |StormException-------|RainedOut
- * */
- //演示抽象类的异常处理
- abstract class Inning{
- public void Inning() throws BaseException{}
- public void event() throws BaseException{}
- public abstract void atBat() throws AException, BException;
- public void walk(){} //不抛出任何异常
- }
- //演示接口的异常处理
- interface Storm{
- public void event() throws RainedOut; //和抽象类一样的方法,不同异常声明
- public void rainHard() throws RainedOut;
- }
- //这是我们的主要关注点
- class StormyInning extends Inning implements Storm{
- //能为构造器添加新的异常,但必须处理已有的异常
- public StormyInning() throws BaseException, RainedOut{}
- public StormyInning(String s)throws BaseException, AException{}
-
- //不能添加新的异常
- //public void walk() throws AException{}
-
- //接口不能为父类继承来的方法添加新的异常
- //可以不写父类的异常声明
- public void event(){}
-
- //如果不是父类方法,则可以
- @Override
- public void rainHard() throws RainedOut {}
-
- //重写的方法可以抛出父类声明的异常的子类
- @Override
- public void atBat() throws UpperAException {}
- }
- public class ExceptionDemo3 {
- public static void main(String[] args) {
- try {
-
- //s1必须初始化,因为有可能构造失败
- StormyInning s1 = null;
- //用子try-catch处理构造函数异常
- try {
- s1 = new StormyInning();
- } catch (RainedOut e) {
- e.printStackTrace();
- } catch (BaseException e) {
- e.printStackTrace();
- }
- s1.atBat();
-
- } catch (UpperAException e) {
- System.out.println("UpperAException");
- }
-
- //看看向上转型会发生什么
- Inning s2 = null;
- try {
- s2 = new StormyInning();
- } catch (RainedOut | BaseException e) {
- //必须处理基类声明的异常
- System.out.println("RainedOut");
- }
-
- //只能抛出基类声明的异常
- try {
- s2.atBat();
- } catch (AException | BException e) {
- System.out.println("A or BException");
- }
- }
- }
复制代码
|
|