java:如何声明final在try-catch块中初始化的变量? [英] java: how to declare final a variable that is initialized inside a try - catch block?
问题描述
我有一个变量,它不应该在初始化后改变它的值,所以我想把它定义为最终变量。
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.
问题在于变量必须在try块内初始化,所以我遇到以下麻烦:
the problem is that the variable has to be initialized inside a try block, so I get the following troubles:
我有以下代码:
Connection conn = null;
try {
conn = getConn(prefix);
[...do some stuff with conn...]
} catch (Exception e) {
throw new DbHelperException("error opening connection", e);
} finally {
closeConnection(conn);
}
如果我将变量声明为final,而不将其初始化为null,我得到在finally块上的'局部变量conn可能尚未初始化'。另一方面,如果我将其声明为final并将其初始化为null,则会在try块中收到错误无法分配最终局部变量conn。
If I declare the variabale as final, without initializing it to null, I get a 'The local variable conn may not have been initialized' on the finally block. On the other hand, if I declare it final and initialize it to null, I get the error 'The final local variable conn cannot be assigned' in the try block.
编辑:在lxx回答后,我带来了这个版本
after lxx answer, I came with this version
try {
final Connection conn = conn = getConn(prefix);
try {
return selectAll(conn, sql, params);
} catch (Exception e) {
throw new DbHelperException("error executing query", e);
} finally {
closeConnection(conn);
}
} catch (Exception e) {
throw new DbHelperException("error opening connection", e);
}
所以这应该是这样做的方法吗?
So this should be the way to do it?
-
获得的经验教训:
我认为正确答案问题是lxx给出的问题,但在这种情况下,我猜是宣布变量最终的利弊超过了它的好处......
I think that the correct answer to the question is the one that lxx gave, but in this case I guess that the cons of declaring the variable final outweights it's benefits...
-
编辑:发现有关何时使用最终的堆栈溢出的两个问题
found two questions on stack overflow about when to use final
< a href =https://stackoverflow.com/questions/137868/using-final-modifier-whenever-applicable-in-java>使用final和final。适用于java的修饰符
推荐答案
您可以更准确地处理异常。如果你得到一个Exception打开连接,你不必在finally块中关闭它我猜。如果之后得到异常,则在try块中,并在新的嵌套try-catch块中处理异常,您不需要在外部定义变量。类似于:
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);
}
这篇关于java:如何声明final在try-catch块中初始化的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!