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

后端 未结 5 1490
独厮守ぢ
独厮守ぢ 2020-12-18 00:40

I have some code with this structure:

public void method() {
    Object o;
    try {
        o = new Object();
    } catch (Exception e) {
        //Processi         


        
5条回答
  •  温柔的废话
    2020-12-18 01:20

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

提交回复
热议问题