Topic: A question on Exception,pls help..really need some explanation. |
Print this page |
1.A question on Exception,pls help..really need some explanation. | Copy to clipboard |
Posted by: JiafanZhou Posted on: 2005-11-18 21:32 A question abt the Exception thrown among the superclass and subclass. "Why the subclass overriden method can not throw an Exception whose type is bigger than the counterpart method in the superclass? Is there any reason in the JVM which can demonstrate this idea?" The following code can show my idea. D:\>C:\Java\jdk1.5.0_05\bin\javac test.java test.java:11: method() in AAA cannot override method() in Test; overridden metho d does not throw java.lang.Exception public void method() throws Exception { ^ 1 error I know this is not a big issue, just want to know why. |
2.Re:A question on Exception,pls help..really need some explanation. [Re: HenryShanley] | Copy to clipboard |
Posted by: anatoranato Posted on: 2005-11-19 05:59 如果不这样做的话程序中可能会存在潜在的错误,还是来看下面的例子吧. class CanNotTasteException extends Exception {} class TasteFailException extends Exception {} class Fruit { public String taste() throws CanNotTasteException{ return "good"; } } class banana extends Fruit{ public String taste() throws Exception{ throw new TasteFailException(); } } public class Test{ public void test(Fruit afruit){ try{ afruit.taste(); } catch(CanNotTasteException e){ System.out.println("got it"); } } public static void main(String [] args){ new Test().test(new banana()); } } 你可以看到,如果这个代码是可以被编译通过的话,在执行的时候,必然出错.事实上,当你使用某个类族里的年长的类时,你应当捕获处理它有可能抛出的那个种类的异常,但是如果允许子类覆盖父类的方法时,可以抛出比被覆盖方法所抛出的异常的范围还要广的异常时,父类的使用者很可能就会出现如上例所示的错误. |
3.Re:A question on Exception,pls help..really need some explanation. [Re: HenryShanley] | Copy to clipboard |
Posted by: JiafanZhou Posted on: 2005-11-21 16:56 superb,excellent explanation, thx,anatoranato . |
Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1 客服电话 18559299278 客服信箱 714923@qq.com 客服QQ 714923 |