I have some code like so:
public class Foo {
private int x;
public Foo() {
}
public Foo(int x) {
try {
//do some initialisation stuff like:
this.x = x;
}
catch(Exception ge){
//call empty constructor not possible
//this();
//this.EMPTY();
//Foo();
}
}
public static final Foo EMPTY = new Foo();
}
I'd like to know if it is possible to achieve something such as this (I know that calling another constructor must be the first statement in the constructor). I have looked around here on SO but haven't found anything as such, leading me to believe that perhaps, I ought to handle the error logic in the instantiating method.
Just change the execution order :
public class Foo {
Integer i;
public Foo() {
System.out.println("Empty constructor invoked");
}
public Foo(Integer i) {
this(); //can be omitted
try {
System.out.println("i initialized to : "+i.toString());
} catch (Exception ex) {
System.out.println("i NOT initialized ");
}
}
public static void main(String[] args) {
new Foo(); //prints: Empty constructor invoked
new Foo(5);//prints: Empty constructor invoked
//prints: i initialized to : 5
new Foo(null);//prints: Empty constructor invoked
//prints: i NOT initialized
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With