If the constructor ends up with an exception, is the object created exactly the same with a normal 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 is:
Exception: java.lang.Exception
f(): entry.
If you catch the exception, the constructed object is never passed back to the caller, and the caller’s result variable is not set. However, the static variable would, in theory, be set, and I can’t see any reason why it would not be accessible.
Note, however, that method verification will not allow you to store
thisuntil after thesuperconstructor is called, so this is not a “back door” into otherwise protected objects.Since it’s your object, “safe” is up to you.
[A little more detail: When the compiled version of your constructor is entered, the “raw” Java object is fully constructed — no additional work is needed by the system to make it valid. The
superconstructor has not been called yet, however, and it’s either up to you to explicitly make asupercall or have the compiler insert thesupercall by default (which it will do at the start of the method if you don’t have an explicit call). The “bytecode verifier” in the JVM has some very strict rules about what can happen in a constructor prior to calling thesuperconstructor, and storingthisto a static would be a definite no-no — you’d get a VerifyError.]