java: how to declare final a variable that is initialized inside a try - catch block?

前端 未结 4 2019
迷失自我
迷失自我 2021-01-01 19:14

I have a variable that is not supposed to change its value after it\'s been initialized, so I want to define it as a final variable.

the problem is that the variable

4条回答
  •  情书的邮戳
    2021-01-01 19:41

    You could handle the Exceptions more accurately. If you get an Exception opening the connection, you don't have to close it in the finally block I guess. If you get an exception after that, in the try block, and handle the exception in a new nested try-catch block you don't need to define the variable outside. Something like:

        try {
            final Connection conn = getConn(prefix);
            try {
                //code using conn
            } catch (Exception e) {
    
            } finally {
                closeConnection(conn);
            }
        } catch (DbHelperException e) {
            throw new DbHelperException("error opening connection", e);
        }
    

提交回复
热议问题