异常

2019-10-26  本文已影响0人  后来丶_a24d

目录

目录.png

异常概览

异常.png

细节说明

一个失败的方法调用应该使对象处于调用之前的状态

try with resource

public static void main(String[] args) throws IOException {
        //资源规范头里面的资源会被关闭,因为InputStream实现了AutoCloseable
        try(
                InputStream in = new FileInputStream(new File("TryWithResources.java"))
        ) {
            int contents = in.read();
            // 这里是抛出IOE exception, 异常子类匹配也可以,也可以加|处理
        } catch(Exception e) {
            System.out.println("test");
        }

    }

异常限制

class BaseballException extends Exception {}
class Foul extends BaseballException {}
class Strike extends BaseballException {}
class StormException extends Exception {}
class RainedOut extends StormException {}
class PopFoul extends Foul {}

abstract class Inning {
    Inning() throws BaseballException {}
    public void event() throws BaseballException {
    }
    public abstract void atBat() throws Strike, Foul;
    public void walk() {}
}
interface Storm {
    void event() throws RainedOut;
    void rainHard() throws RainedOut;
}
public class StormyInning extends Inning implements Storm{
    // 子类构造器可以新增异常
    public StormyInning() throws RainedOut, BaseballException {}
    // 编译不通过,继承的时候异常只能基类的更小集合
    // void walk() throws PopFoul {}
    // 接口不能向基类中的现有方法添加异常:
    // public void event() throws RainedOut {}
    @Override
    public void rainHard() throws RainedOut {}
    // 可以不抛异常继承
    @Override
    public void event() {}
    // 可以选择抛出子异常
    @Override
    public void atBat() throws PopFoul {
        throw new PopFoul();
    }
    public static void main(String[] args) {
        try {
            StormyInning si = new StormyInning();
            si.atBat();
        } catch(PopFoul e) {
            // 子类就根据子类来
            System.out.println("Pop foul");
        }  catch(RainedOut e) {
            System.out.println("Rained out");
        } catch(BaseballException e) {
            System.out.println("Generic baseball exception");
        }
        try {
            Inning i = new StormyInning();
            i.atBat();
        } catch(Strike e) {
            System.out.println("Strike");
        } catch(Foul e) {
            // 基类的异常则根据基类来,并结合子类,子类没抛Strike异常,则不会走第一个异常
            System.out.println("Foul");
        } catch(RainedOut e) {
            System.out.println("Rained out");
        } catch(BaseballException e) {
            System.out.println("Generic baseball exception");
        }
    }
}


参考文章

上一篇 下一篇

猜你喜欢

热点阅读