Possible Duplicate:
How to handle a static final field initializer that throws checked exception
In this example, I get the error The blank final field myClass may not have been initialized:
private final static MyClass myClass; // <-- error
static {
try {
myClass = new MyClass(); // <-- throws exception
myClass.init();
} catch (Exception e) {
// log
}
}
In that example, I get the error The final field myClass may already have been assigned:
private final static MyClass myClass;
static {
try {
myClass = new MyClass(); // <-- throws exception
myClass.init();
} catch (Exception e) {
myClass = null; // <-- error
// log
}
}
In there any solution to that issue?
Declaring final variable without initialization If you declare a final variable later on you cannot modify or, assign values to it. Moreover, like instance variables, final variables will not be initialized with default values. Therefore, it is mandatory to initialize final variables once you declare them.
Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.
2. Java Error: “variable might not have been initialized” Should we declare a local variable without an initial value, we get an error. This error occurs only for local variables since Java automatically initializes the instance variables at compile time (it sets 0 for integers, false for boolean, etc.).
Once we create a local variable we must initialize it before using it. Since the local variables in Java are stored in stack in JVM there is a chance of getting the previous value as default value. Therefore, In Java default values for local variables are not allowed.
private final static MyClass myClass;
static {
MyClass my;
try {
my = new MyClass();
my.init();
} catch (Exception e) {
my = null;
// log
}
myClass = my; //only one assignment!
}
Here's a solution :
private final static MyClass myClass = buildInstance();
private static MyClass buildInstance() {
try {
MyClass myClass = new MyClass();
myClass.init();
return myClass;
} catch (Exception e) {
return null;
}
}
If your class is final it can't change values once it is initialised.
What you are doing in the second snippet is that you are first assigning it to new MyClass()
and then if an Exception is thrown in init()
you then change it to null
.
This is not allowed. If new MyClass()
does not throw an Exception why don't you put it at the top line?
Warning though, that if init()
throws an Exception, you will still have an unintialised instance of MyClass
. It doesn't seem that the way you're working with this class matches the way its designed to work.
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