Historically I have always written my Exception handling code like this:
Cursor cursor = null;
try {
cursor = db.openCursor(null, null);
// do stuff
} finally {
if (cursor != null) cursor.close();
}
But recently, for reasons of readability and laziness, I have started to do this:
Cursor cursor = db.openCursor(null, null);
try {
// do stuff
} finally {
cursor.close();
}
Am I wrong to have the assignment to cursor (jdbc handle, whatever) out of the try-catch-finally block?
Barring the JVM actually blowing up on the assignment, or inbetween the assignment and the first line of whatever is in the try block I’m not sure if my old style was lending any extra value, and the second is certainly more readable and concise. The literature generally always does go with the first style though.
EDIT – assume I’m happy for any exceptions thrown by openCursor while initialising the cursor not to be caught in this block of code, my only concern for this example is closing the cursor if it is assigned & opened. Also assume I’m testing for nulls etc.. etc.. yadda… yadda… (I have changed the example to reflect this, it wasn’t the focus of my question so I didn’t include it in the first version)
If all you are doing in your finally is closing the cursor then the second form is correct. You will never have a cursor to close if openCursor() fails. The value of that variable won’t even have been set.
As others allude to, the caveats are if you are doing additional initialization that requires its own clean up then that will logically have to go in the finally{} and change the scope accordingly. Though I’d argue for a restructuring in that case.
The bottom line: as written the first version is needlessly complicated. The second version is correct.
Edit: Incorporating my other comments for posterity…
The first example might seem harmless as all it does is add a bunch of needless code. (Completely needless, if that wasn’t clear.) However, in classic “more code means more potential bugs” fashion, there is a hidden gotcha.
If for some reason the “// do something” code inadvertently clears the cursor variable then you will silently leak cursors whereas before you’d at least have gotten a NullPointerException. Since the extra code does absolutely nothing useful, the extra risk is completely unnecessary.
As such, I’m willing to call the first example “just plain wrong”. I’d certainly flag it in a code review.