Your idea is correct: The finally block will close the resources even if an unexpected exception ocurred.
You are also right that this is irrelevant if such an exception crashes the complete application, but from looking at this code you can't decide if this is the case. There might be other exception handlers, catching that exception, so it is good and correct practice to put the closing logic in a finally block.
Note that there still might be a bug hiding: if data.close()
throws an exception, result.close()
will never get called.
Depending on your environment there are various flavours on how to fix the bug.
in java 7 ff you can use try-with-resources
if you are using Spring, there might be a proper template similar to the JdbcTemplate
if nothing of those applies, yes you'll have to do a try/finally inside the finally. Quit ugly. You absolutely should at least extract this into a method as suggested in the comments.
conceptually cleaner but rather wordy in java pre 8 is to implement the loan pattern. If you don't happen to work with scala/clojure/haskell developers it might be more confusing then anything else.