class AbortedConstruction extends Exception {
  public AbortedConstruction() {
    super("Construction aborted");
  }
}class WithCleanup {
  private boolean constructed = false;
  public WithCleanup(boolean abort)
    throws AbortedConstruction {
    // Perform construction that might be
    // unsucessful (and throw an exception) here.
    if(abort) throw new AbortedConstruction();
    System.out.println("After exception");
    constructed = true;
  }
  public void cleanup() {
    System.out.println(
      "constructed = " + constructed);
    if(constructed == true)
      System.out.println("Cleaning up");
    else
      System.out.println(
        "Constructor didn't finish,"+
        "not cleaning up");
  }
}
public class E14_CleanupFlag {
  public static void main(String args[]) {
    WithCleanup wc = null;
    try {
      wc = new WithCleanup(false);
    } catch(AbortedConstruction e) {
      System.out.println("Caught " + e);
    } finally {
      System.out.println(
        "In finally 1, preparing to clean up");
      wc.cleanup();
    }
    wc = null; // Very important!
    try {
      try {
        wc = new WithCleanup(true);
      } catch(AbortedConstruction e) {
        System.out.println("Caught " + e);
      } finally {
        System.out.println(
          "In finally 2, preparing to clean up");
        wc.cleanup();//为什么这里的wc=null,因而不能调用cleanup(),
      }              //导致抛出java.lang.NullPointerException,
                     //finally的作用范围应该在哪里?
                     //这是thinking in java的一道异常的习题的答案
    } catch(Exception e) {
      System.out.println("Caught exception "+ e);
    }
  }
}

解决方案 »

  1.   

    public class E14_CleanupFlag {
    public static void main(String args[]) {
    WithCleanup wc = null;
    try {
    wc = new WithCleanup(false);
    } catch(AbortedConstruction e) {
    System.out.println("Caught " + e);
    } finally {
    System.out.println(
    "In finally 1, preparing to clean up");
    wc.cleanup();
    }
    wc = null; // Very important!//wc为null;
    try {
    try {
    wc = new WithCleanup(true);//new 不成功,在构造函数里抛Exception了,wc=null;
    } catch(AbortedConstruction e) {
    System.out.println("Caught " + e);
    } finally {
    System.out.println(
    "In finally 2, preparing to clean up");
    wc.cleanup();//为什么这里的wc=null,因而不能调用cleanup(),//上面没赋值成功,当然是null
    } //导致抛出java.lang.NullPointerException,
    //finally的作用范围应该在哪里?//跟finally没关系,只跟括号有关
    //这是thinking in java的一道异常的习题的答案
    } catch(Exception e) {
    System.out.println("Caught exception "+ e);
    }
    }
    }