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

后端 未结 5 1400
独厮守ぢ
独厮守ぢ 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:06

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

    0 讨论(0)
  • 2020-12-18 01:13

    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!

    0 讨论(0)
  • 2020-12-18 01:18

    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); 
    }
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2020-12-18 01:22

    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

    0 讨论(0)
提交回复
热议问题