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

江枫思渺然 提交于 2019-11-30 03:58:29

问题


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?


回答1:


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




回答2:


Initialize your object: Object o = null;, however watch out for the NullPointerExceptions that might be thrown when you give it to the method calls.




回答3:


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);
}



回答4:


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!




回答5:


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); 
}


来源:https://stackoverflow.com/questions/18099320/the-local-variable-might-not-have-been-initialized-detect-unchecked-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!