What you're describing in Java is very similar in C# (there the message would be CS0165 Use of unassigned local variable 'someObject'
). The solution in both languages is to make a null-assignment:
SomeClass someObject = null;
and the warning will go away. As the other answers were describing, the reason is simply that the compiler isn't smart enough, so those warnings are kind of a trade-off.
Complete Java example:
class SomeClass
{
public int someMethod()
{
return 1;
}
}
public class JavaFiddle
{
public static SomeClass someOperation()
{
SomeClass result = new SomeClass();
return result;
}
public static void main(String[] args)
{
SomeClass someObject = null;
boolean success = true;
try {
someObject = someOperation();
} catch (Exception e) {
success = false;
}
if (success) {
int number = Integer.valueOf(someObject.someMethod());
}
}
}
Paste this code in a JavaFiddle
(press Ctrl and left-click to open a tab with JavaFiddle)
> Compiling...
> Running...
As you can see, in the code above the issue is already fixed, so if you paste it into the JavaFiddle tool, it will run as expected without error.
To provoke the error, change the code as follows:
SomeClass someObject; // = null;
and run it again. You will get the message:
> Compiling...
/str/JavaFiddle.java:29: error: variable someObject might not have been initialized
int number = Integer.valueOf(someObject.someMethod());
^
1 error
Note that I just took the example you provided "as is" - you should consider the hints given regarding exception handling (see comment to your question from Eric Lippert). Swallowing exceptions without really handling them usually isn't good - better deal with the cases you know in the code and let the caller handle any exceptions that might occur you don't know about (and, of course implement some logging).