variable might already have been assigned when it cannot be assigned

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

research this code:

public class TestFinalAndCatch {
    private final int i;

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


        
4条回答
  •  梦毁少年i
    2021-01-17 20:01

    The problem is that in this case compiler works syntax-based not semantic-based. There are 2 workarounds: First base on moving exception handle on method:

    package com.java.se.stackoverflow;
    
    public class TestFinalAndCatch {
        private final int i;
    
        TestFinalAndCatch(String[] args) {
            i = method1();
        }
    
        static int method1() {
            try {
                return 1;
            } catch (Exception ex) {
                return 0;
            }
        }
    }
    

    Second base on using temporar variable:

    package com.java.se.stackoverflow;
    
    import java.io.IOException;
    
    public class TestFinalAndCatch {
        private final int i;
    
        TestFinalAndCatch(String[] args) {
            int tempI;
            try {
                tempI = method1();
            } catch (IOException ex) {
                tempI = 0;
            }
            i = tempI;
        }
    
        static int method1() throws IOException {
            return 1;
        }
    }
    

提交回复
热议问题