java 异常限制_java 异常的限制

packageexceptions;//: exceptions/StormyInning.java//Overridden methods may throw only the exceptions//specified in their base-class versions, or exceptions//derived from the base-class exceptions.

class BaseballException extendsException {}class Foul extendsBaseballException {}class Strike extendsBaseballException {}abstract classInning {public Inning() throwsBaseballException {}public void event() throwsBaseballException {//Doesn't actually have to throw anything

}public abstract void atBat() throwsStrike, Foul;public void walk() {} //Throws no checked exceptions

}class StormException extendsException {}class RainedOut extendsStormException {}class PopFoul extendsFoul {}interfaceStorm {public void event() throwsRainedOut;public void rainHard() throwsRainedOut;

}public class StormyInning extends Inning implementsStorm {//OK to add new exceptions for constructors, but you//must deal with the base constructor exceptions:

publicStormyInning()throwsRainedOut, BaseballException {}publicStormyInning(String s)throwsFoul, BaseballException {}//Regular methods must conform to base class://! void walk() throws PopFoul {}//Compile error//Interface CANNOT add exceptions to existing//methods from the base class://! public void event() throws RainedOut {}//If the method doesn't already exist in the//base class, the exception is OK:

public void rainHard() throwsRainedOut{}//You can choose to not throw any exceptions,//even if the base version does:

public voidevent() {}//Overridden methods can throw inherited exceptions:

public void atBat() throwsPopFoul{}//public void atBat() throws PopFoul,RainedOut {}不能throws出基类方法没有的异常

public static voidmain(String[] args) {try{

StormyInning si= newStormyInning();

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");

}//Strike not thrown in derived version.

try{//What happens if you upcast?

Inning i = newStormyInning();

i.atBat();//You must catch the exceptions from the//base-class version of the method:

} 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");

}

}

}///:~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值