If the constructor ends with an exception, is the same object created with normal?

If the constructor ends with an exception, is the object created exactly the same as the regular one?

class A {

    static A o;

    A() throws Exception {
        o=this;
        throw new Exception();
    }

    void f() { System.out.println("f(): entry."); };

    static public void main(String[]args ) {
        try {
         A o =new A();
        }
        catch (Exception e) {
              System.out.println("Exception: " + e);
        }

        A.o.f(); // Is it safe to use this object?
       }
}

This compiles and runs, and the output of this program:

Exception: java.lang.Exception
f(): entry.
+3
source share
2 answers

If you catch an exception, the constructed object never returns back to the caller, and the caller’s result variable is not set. However, a static variable would theoretically be set, and I see no reason why it would not be available.

, , this , super, " " , .

, "" .

[ : , "" Java - , . super , super super ( ). " -" JVM , super, this - - VerifyError.]

+3
 A.o.f(); // Is it safe to use this object?

Java-, , Java. undefined Java.

, . , , , , , .

, , A

public class S extends A {
  boolean dirty;

  S() throws Exception {
    // Do work to maintain important security invariants.
    dirty = true;
  }

  void foo() {
    if (dirty) {
      System.out.println("clean");
      dirty = false;
    }
    System.out.println("foo");
  }

  public static void main(String... argv) {
    try {
      new S();
    } catch (Exception ex) {}
    // Now A.o is an instance of S, but S constructor
    // was never called.
    S s = (S) A.o;  // works.
    s.foo();  // Never prints clean before printing foo.
  }
}
+2

All Articles