Once i have been asked by some one why do u use finally block ? i said if i want to execute some code irrespective excpton caught or not. like close the connection.. and then he asked is this is good to put code in finally block ,doesnt it create some sort of overhead. if u awant to close the connection , u can put the line 'connection.close(); ' in end of try block and in the end of each catch block. plz discuss it.
Ernest Friedman-Hill
,
author and iconoclast
staff
Ask your friend why he thinks duplicate code is a good thing. Ask him which version, his or yours, would be easier to maintain when new catch clauses were added? Finally, ask him why there would be added overhead for a finally block, given that there's already an exception handler in place?
And even if there were noticable overhead in using a finally block (which I doubt), maintainability still overrides performance by default. BTW, if you duplicate code, it will be less often executed, less often analyzed and optimized by the Hotspot engine - and therefore be slower! (Well, this is a painfully oversimplified view, of course, but might still be a good counterargument to your friend...)
Not only that, what does he do if an exception happens in your "catch" block before "close()" gets called? With a finally clause, you're guaranteed it will be called.
William Brogden
,
Author and all-around good cowpoke
<rant>This preoccupation with overhead is a widespread evil that can lead to nothing but trouble. Having some idea about which operations are expensive and which are cheap is great but your primary focus should be on making code that is correct and clear so it can be easily maintained. </rant> Bill
"This preoccupation with overhead is a widespread evil that can lead to nothing but trouble. Having some idea about which operations are expensive and which are cheap is great" Humm, you seem to have contridicted yourself in a meaningful way
William Brogden
,
Author and all-around good cowpoke
I think there is a difference between being preoccupied with minutia - as evidenced in the question about using finally, and being able to recognize and avoid intrisically expensive operations. Maintaining clarity should take priority in any case.
Bill [ January 19, 2004: Message edited by: William Brogden ]