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)