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能捕捉基础类违例和衍生类违例,但是若将基础类捕获从句置于第一位,试图“屏蔽”衍生类违例,这样做是不行的。