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 has to be initialized inside a try block, so I get the following troubles:
I have the following code:
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);
}
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.
EDIT: 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?
--
Lesson learned:
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...
--
EDIT: found two questions on stack overflow about when to use final
When should one use final for method parameters and local variables?
Using "final" modifier whenever applicable in java
No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.
Yes you can write try without catch. In that case you require finally block. Try requires either catch or finally or both that is at least one catch or finally is compulsory.
The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error. Both catch and finally are optional, but you must use one of them.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With