Question 73
Given: 
11. static classA 

12. void process() throws Exception { throw new Exception(); } 
13. } 
14. static class B extends A { 
15. void process() { System.out.println("B ")} //问题一:为什么在这儿不出错,我是这样想的:A类中process方法有throws Exception,所以继承类中应该与被继承保持一致,也就是应该加上throws Exception才对啊。所以答案我选了D。
16. } 
17. public static void main(String[] args) { 
18.A a=new B(); 
19. a.process(); 
20.} 
What is the result? 
A. B 
B. The code runs with no output. 
C. An exception is thrown at runtime. 
D. Compilation fails because of an error in line 15. 
E. Compilation fails because of an error in line 18. 
F. Compilation fails because of an error in line 19. 
Answer: F问题二:我在eclipse中输入题目中的代码进行测试时,刚输入 static class A{},就被提示:Illegal modifier for the class A; only public, abstract & final are permitted,是题目本来就有错吗?

解决方案 »

  1.   


    public class Test
    {  
      static class A 
      {
        void process() throws Exception 
        { 
          throw new Exception(); 
        } 
      }  
      static class B extends A 
      { 
        void process() 
        { 
          System.out.println("B ");
        } 
      }  
      public static void main(String[] args) { 
        A a=new B(); 
        a.process(); 
      }
    }的确是第19行出错,错误的确正如楼主所说B的process方法没有throws Exception,但这个编译方法本身的时候没问题,下面main里面调用的时候才出现问题
    1 error found:
    File: C:\Documents and Settings\Administrator\Desktop\Test.java  [line: 19]
    Error: C:\Documents and Settings\Administrator\Desktop\Test.java:19: unreported exception java.lang.Exception; must be caught or declared to be thrown
      

  2.   

    有意思,  还要继承throws Exception,  没遇见过
      

  3.   

    的确是第19行出错,错误的确正如楼主所说B的process方法没有throws Exception,但这个编译方法本身的时候没问题,下面main里面调用的时候才出现问题 
      

  4.   


    //就算你这样写也是同样的地方出现异常:
    public class Test {
    static class A 
      {
        void process() throws Exception 
        { 
          throw new Exception(); 
        } 
      }  
      static class B extends A 
      { 
        void process() throws Exception 
        { 
          System.out.println("B ");
        } 
      }  
      public static void main(String[] args) { 
       A a=new B(); 
    a.process();
      }}
    //解决方法是在a.process()抛出异常,主要因为异常没处理的原因
    public class Test {
    static class A 
      {
        void process() throws Exception 
        { 
          throw new Exception(); 
        } 
      }  
      static class B extends A 
      { 
        void process() 
        { 
          System.out.println("B ");
        } 
      }  
      public static void main(String[] args) { 
        A a=new B(); 
        try {
    a.process();
    } catch (Exception e) {
    e.printStackTrace();
    }
      }}