variable might already have been assigned when it cannot be assigned

后端 未结 4 2122
梦如初夏
梦如初夏 2021-01-17 19:31

research this code:

public class TestFinalAndCatch {
    private final int i;

    TestFinalAndCatch(String[] args) {
        try {
            i = method1()         


        
4条回答
  •  醉酒成梦
    2021-01-17 20:13

    To overcome this problem, use a local variable in the try catch block and then assign that result to the instance variable.

    public class TestFinalAndCatch {
        private final int i;
    
        TestFinalAndCatch(String[] args) {
            int tmp;
            try {
                tmp = method1();
            } catch (IOException ex) {
                tmp = 0;
            }
            i = tmp;
        }
    
        static int method1() throws IOException {
            return 1;
        }
    }
    

提交回复
热议问题