zoukankan      html  css  js  c++  java
  • java学习笔记-9.违例差错控制

     

    1.违例规范是告诉程序员这个方法可能抛出哪些类型的异常。他的格式在方法声明中,位于自变量(参数)列表的后面,如void f() throws tooBig, tooSmall, divZero { //...,这样就就告诉我们这个f方法可抛出toobig,toosmall等类型的异常。

    2.在继承里,如果父类的方法没有定义违例规范,则派生类也不能定义。接口中的方法不能改变父类里同样方法的违例接口。如果父类方法有违例规范,衍生类相应的方法可以没有。衍生类的方法可以有继承的违例规范。

    class BaseballException extends Exception {}
    class Foul extends BaseballException {}
    class Strike extends BaseballException {}
    abstract class Inning {
    Inning() throws BaseballException {}
    void event () throws BaseballException {
    // Doesn't actually have to throw anything
    }
    abstract void atBat() throws Strike, Foul;
    void walk() {} // Throws nothing
    }
    class StormException extends Exception {}
    class RainedOut extends StormException {}
    class PopFoul extends Foul {}
    interface Storm {
    void event() throws RainedOut;
    void rainHard() throws RainedOut;
    }
    public class StormyInning extends Inning
    implements Storm {
    // OK to add new exceptions for constructors,
    // but you must deal with the base constructor
    // exceptions:
    StormyInning() throws RainedOut,
    BaseballException {}
    StormyInning(String s) throws Foul,
    BaseballException {}
    // 如果父类的方法没有定义违例规范,则派生类也不能定义
    //! void walk() throws PopFoul {} //Compile error
    // 接口中的方法不能改变父类里同样方法的违例接口
    //! public void event() throws RainedOut {}
    //这样可以
    public void event() throws BaseballException{}
    // 如果父类方法有违例规范,衍生类相应的方法可以没有
    public void rainHard() throws RainedOut {}
    // You can choose to not throw any exceptions,
    // even if base version does:
    public void event() {}
    // Overridden methods can throw
    // inherited exceptions:
    void atBat() throws PopFoul {}
    public static void main(String[] args) {
    try {
    StormyInning si = new StormyInning();
    si.atBat();
    } catch(PopFoul e) {
    } catch(RainedOut e) {
    } catch(BaseballException e) {}
    // Strike not thrown in derived version.
    try {
    // What happens if you upcast?
    Inning i = new StormyInning();
    i.atBat();
    // You must catch the exceptions from the
    // base-class version of the method:
    } catch(Strike e) {
    } catch(Foul e) {
    } catch(RainedOut e) {
    } catch(BaseballException e) {}
    3.finally是try语句块中不管有没有异常,在try完之后都会调用finally语句的内容。
    4.catch能捕捉基础类违例和衍生类违例,但是若将基础类捕获从句置于第一位,试图“屏蔽”衍生类违例,这样做是不行的。
  • 相关阅读:
    arcgis api for js入门开发系列二十打印地图的那些事
    arcgis api 3.x for js 入门开发系列十九图层在线编辑
    arcgis api 3.x for js 入门开发系列十八风向流动图(附源码下载)
    influxDB 0.9 C# 读写类
    [InfluxDB] 安装与配置
    分布式,集群,冗余的理解
    CentOS 7.0系统安装配置图解教程
    InfluxDB学习之InfluxDB的基本操作| Linux大学
    InfluxDB v1.6.4 下载
    InfluxDB中文文档
  • 原文地址:https://www.cnblogs.com/junshijie/p/7009799.html
Copyright © 2011-2022 走看看