在thinking in java书中,有一个题目:
试证明,派生类的构造器不能捕获它的基类构造器所抛出的异常。请问怎么用程序证明??

解决方案 »

  1.   

    public class TestConstructor { /**
     * @param args
     */
    public static void main(String[] args) {
    new Derive("@@@@@@"); }}class Super {

    public Super() throws Exception {
    throw new Exception();

    }
    }
    class Derive {
    public Derive(String s) {
    super(); //调用父类构造函数
    System.out.println(s);
    }

    }
      

  2.   

    不好意思呵呵 是这样 因为 父类的构造函数只能在子类构造函数的第一行调用但是如果你要catch异常肯定要try { //调用父类构造函数
    }这样又与上面规定矛盾 因为不在第一行所以不能catch 只能throws
      

  3.   

    try 
    {
      super();
    }语法有错.
    你如果不这样写,编译器又默认把super()放在第一行
    super();
    try 
    {
     }  又捕不到所以....
      

  4.   

    // exceptions/Ex21.java// TIJ4 Chapter Exceptions, Exercise 21, page 488// Demonstrate that a derived-class constructor cannot catch exceptions thrown// by its base-class constructor.class BaseException extends Exception {}class Base { Base() throws BaseException { throw new BaseException(); }}class Derived extends Base { // BaseException must be caught (no way) or // declared to be thrown: Derived() throws BaseException { super(); // not this way, 'catch' without 'try' not allowed: // catch(BaseException e) {} // not this way either, because call to super // must be first statement in constructor: // try { // super(); // } catch(BaseException e) {} }}public class Ex21 { public static void main(String[] args) { try { Derived d = new Derived(); } catch(BaseException e) { System.out.println("BaseException caught in main()"); } }}