Java exception handling – style
Historically, I have written my exception handling code:
Cursor cursor = null; try { cursor = db.openCursor(null,null); // do stuff } finally { if (cursor != null) cursor.close(); }
But recently, due to readability and laziness, I have begun to do this:
Cursor cursor = db.openCursor(null,null); try { // do stuff } finally { cursor.close(); }
My error is to assign a JDBC handle (whatever) to a try catch finally block?
I don't know if my old style lends any additional value, except that the JVM is actually trying to block anything on the job, or between the task and the first line, and the second must be more readable and concise Literature generally always goes with the first style
Edit - suppose I'm happy with any exception thrown by opencursor, and the initialization cursor is not caught in this code block, my only concern is that this example is to close the cursor if it is allocated & open Also suppose I'm testing nulls et al Wait Yadda... Yadda... (I have changed the example to reflect this. This is not the focus of my problem, so I didn't include it in the first edition)
Solution
If all you end up doing is closing the cursor, the second form is correct If opencursor() fails, you will never have a closed cursor The value of this variable will not even be set
As others have suggested, the caveat is that if you are doing additional initialization and need to clean up yourself, you must logically go to finally {} and change the scope accordingly Although I think restructuring should be carried out in this case
Bottom line: writing the first version is unnecessarily complex The second version is correct
Editor: combine my other comments for future generations
The first example seems harmless because all it does is add a bunch of unnecessary code However, in the classic fashion of "more code means more potential errors", there is a hidden liar
If the "/ / do something" code inadvertently clears the cursor variable for some reason, you will leak the cursor by default before you get at least NullPointerException Because extra code is absolutely useless, the extra risk is completely unnecessary
Therefore, I would like to call the first example "simple error" I will definitely mark it in the code review