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

巧了我就是萌 提交于 2019-11-30 11:26:04

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

How about this?

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

Why do you want it final? If you want to pass it to an anonymous inner class, you could do:

Connection conn = null;
try {
    conn = getConn(prefix);
    final Connection finalConn = conn;
    // pass it to inner class here
} catch (Exception e) {
    throw new DbHelperException("error opening connection", e);
} finally {
    closeConnection(conn);
}

The only problem (and quite a big one) with this solution is that you close your connection as soon as you leave this block. So unless you declare and call your anon inner class straight away, this pattern isn't going to work.

Either way, I'd probably rephrase the whole thing if I were you, making prefix final instead and delegating connection handling to the anon inner class.

Can you try assigning it in both the catch and finally blocks? Like so:

Connection connTemp = null;
final Connection conn;
try {
    connTemp = getConn(prefix);
} catch (Exception e) {
    throw new DbHelperException("error opening connection", e);
} finally {
    closeConnection(conn);
}
conn = connTemp;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!