I have some code with this structure:
public void method() {
Object o;
try {
o = new Object();
} catch (Exception e) {
//Processi
Initialize your object: Object o = null;
, however watch out for the NullPointerException
s that might be thrown when you give it to the method calls.
Just put the doSomething(o)
inside the try { }
block:
public void method() {
Object o;
try {
o = new Object();
doSomething(o);
} catch (Exception e) {
handleError();
}
}
You perhaps dont want to execute doSomething() if the creation of your Object fails!
Instance variable is the Object type so you should initialize value "null"
public void method() {
Object o=null;
try {
o = new Object();
} catch (Exception e) {
handleError();
}
doSomething(o);
}
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);
}
You need to initialize local variables before they are used as below
public void method() {
Object o=null;
try {
o = new Object();
} catch (Exception e) {
handleError();
}
doSomething(o);
}
You will not get the compilation failure until you use local variable which was not initialized