Here is my code snippet:
Someclass someObject;
boolean success = true;
try {
someObject = someOperation();
} catch (Exception e) {
success = false;
}
if (success) {
int number = Integer.valueOf(someObject.someMethord());
}
and within the line:
int number = Integer.valueOf(someObject.someMethord());
the Java compiler throws and error saying
Error: variable someObject might not have been initialized`.
However, if success
equals true
, then there is no way someObject
will not have been initialized, why am I getting this error?
If the compiler believes that a local variable might not have been initialized before the next statement which is using it, you get this error. You will not get this error if you just declare the local variable but will not use it.
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.). However, local variables need a default value because the Java compiler doesn't allow the use of uninitialized variables.
The compiler doesn't analyze the relation between your success
flag and the initialization of the someObject
variable.
As far as the compiler is concerned, someObject
may not be initialized if an exception occurs.
You can solve that issue by setting the variable to null
in your catch block (and instead of checking your success
variable, check that someObject != null
).
Or you can move the int number = Integer.valueOf(someObject.someMethord());
statement inside your try block.
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