<span style="font-size:18px;"> </span>
/*
这个例子是关于异常在继承中的问题,当BException继承AException时,父类抛出AException,那么子类只能抛出AException或BException,而不能抛出其他异常,因为子类不能比父类还“有问题”。下面是例子:
*/
<span style="font-size:18px;">class AException extends Exception { } class BException extends AException { } class Fu { public void show() throws AException { } } class Zi extends Fu { public void show() throws BException //或者抛出 BException { } } class ExceptionDemo3 { public static void main(String[] args) { try{ Fu f = new Fu(); f.show(); }catch(AException e)//只能抛出AException { } try{ Zi z = new Zi(); z.show(); }catch(AException e) //当子类中方法抛出BException时这也要抛出BException { } try{ Fu f = new Zi(); f.show(); }catch(AException e)//只能抛出AException,因为多态 { } } }</span>
时间: 2024-10-27 10:47:15