子类在覆盖父类方法时,父类的方法如果抛出了异常,那么子类的方法只能抛出父类的异常或者该异常的
子类。
如果父类抛出多个异常,那么子类只能抛出父类异常的子集。
简单说:子类覆盖父类只能抛出父类的异常或者子类的子集
package example; class OneException extends Exception{} class TwoException extends Exception{} class a{ public a() throws OneException{ } public void event() throws TwoException{} } public class Test extends a{ public Test() throws TwoException, OneException { super(); } //public void event()throws OneException {} //编译失败 //public void event()throws OneException,TwoException {}//编译失败 public void event()throws TwoException {} }
还可以看出以上说法不适用与构造器方法,异常限制对构造器不起作用,子类构造器可以抛出任何异常,而不必理会基类构造器所抛出的异常,然而
基类构造器必须以这样那样的1方式的被调用,派生类构造器的异常说明必须包含基类构造器的异常说明。
接口对异常限制
package example; class OneException extends Exception{} class TwoException extends Exception{} class ThreeException extends Exception{} class a{ public a() throws OneException{ } public void event() throws TwoException{} } interface B{ public void event()throws ThreeException ; public void show() throws ThreeException; } public class Test extends a implements B{ public Test() throws TwoException, OneException { super(); } //public void event()throws ThreeException {} //编译失败 //public void event()throws TwoException,ThreeException {} //编译失败 //public void event()throws TwoException {}//编译失败 public void event(){ } public void show() throws ThreeException { } }
子类方法抛出的异常可以是基类方法异常的子类
package example; class OneException extends Exception{} class TwoException extends Exception{} class ThreeException extends TwoException{} class a{ public a() throws OneException{ } public void event() throws TwoException{} } public class Test extends a { public Test() throws TwoException, OneException { super(); } public void event() throws ThreeException{ } }