实现的方法中,抛的异常只能比父类或接口中的少
import java.io.IOException; public interface IHello { void say(String msg) throws TestException, IOException; } class IHelloImpl implements IHello { @Override public void say(String msg) throws IOException { System.out.println("msg = [" + msg + "]"); } }
类StormyInning既扩展了基类Inning,又实现了接口Storm,而且基类Inning和接口Storm都声明了方法event():
package com.liush.chapter12;
//Overridden methods may throw only the exceptions specified in their
//base-class versions,or exceptions derived from the base-class exceptions.
class BaseballException extends Exception {}
class Foul extends BaseballException {}
class Strike extends BaseballException {}
abstract class Inning {
public Inning() throws BaseballException {}
public void event() throws BaseballException {
// Doesen't actually have to throw anthing
}
public abstract void atBat() throws Strike,Foul;
public void walk() {} //Throws no checked exceptions
}
class StormException extends Exception {}
class RainedOut extends StormException {}
class EventException extends StormException {}
class PopFoul extends Foul {}
interface Storm{
public void event() throws EventException;
public void rainHard() throws RainedOut;
}
public class StormyInning extends Inning implements Storm{
//OK to add new exceptions for constructor, but you must
//deal with the base constructor exceptions:
public StormyInning() throws RainedOut,BaseballException {}
public StormyInning(String s) throws Foul,BaseballException {}
@Override
public void rainHard() throws RainedOut {
// TODO Auto-generated method stub
}
public void event() {System.out.println("Override the Inning.");}
@Override
public void atBat() throws Strike, Foul {
// TODO Auto-generated method stub
}
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();
Storm k=new StormyInning();
i.event();
k.event();
i.atBat();
}
catch(Strike e) { System.out.println("Strike");}
catch(Foul e) { System.out.println("Foul");}
catch(RainedOut e) { System.out.println("Rained out");}
catch(BaseballException e) { System.out.println("Generic baseball exception");}
catch (EventException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
}
}
说明:类StormyInning既继承了Inning基类,又实现了Storm接口,用基类来建立StormyInning对象时,根据向上转型,event()是被认为是从Inning中来:
而用接口Storm来建立StormyInning对象时,event()则是被认为是从Sorm中来的:
因此,它们抛出异常就决定于它们的基类和接口了:
http://blog.163.com/liu_sheng_han/blog/static/190591372201212394856740/