The local variable might not have been initialized - Detect unchecked exception throw within a method

Luis Sep picture Luis Sep · Aug 7, 2013 · Viewed 17.5k times · Source

I have some code with this structure:

public void method() {
    Object o;
    try {
        o = new Object();
    } catch (Exception e) {
        //Processing, several lines
        throw new Error(); //Our own unchecked exception
    }
    doSomething(o);
}

I have quite a few methods in which I have the same code in the catch block, so I want to extract it to a method so that I can save some lines. My problem is, that if I do that, I get a compiler error " The local variable o might not have been initialized".

public void method() {
    Object o;
    try {
        o = new Object();
    } catch (Exception e) {
        handleError();
    }
    //doSomething(o); compiler error
}


private void handleError() throws Error {
    //Processing, several lines
    throw new Error();
}

Is there any workaround?

Answer

Sanjaya Liyanage picture Sanjaya Liyanage · Aug 7, 2013

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