I have some code with this structure:
public void method() {
Object o;
try {
o = new Object();
} catch (Exception e) {
//Processi
Since o
is getting initialized within the try
block and initializing o
might throw an exception, java thinks that doSomething(o)
statement might reach without o
being initialized. So java wants o
to be initialized incase new Object()
throws exception.
So initializing o
with null
will fix the issue
public void method() {
Object o = null;
try {
o = new Object(); //--> If new Object() throws exception then o remains uninitialized
} catch (Exception e) {
handleError();
}
if(o != null)
doSomething(o);
}