I know how to use try-catch-finally. However I do not get the advance of using finally as I always can place the code after the try-catch block.
Is there any clear example?
I know how to use try-catch-finally. However I do not get the advance of
Share
Update: This is actually not a great answer. On the other hand, maybe it is a good answer because it illustrates a perfect example of
finallysucceeding where a developer (i.e., me) might fail to ensure cleanup properly. In the below code, consider the scenario where an exception other thanSpecificExceptionis thrown. Then the first example will still perform cleanup, while the second will not, even though the developer may think “I caught the exception and handled it, so surely the subsequent code will run.”Everybody’s giving reasons to use
try/finallywithout acatch. It can still make sense to do so with acatch, even if you’re throwing an exception. Consider the case* where you want to return a value.The alternative to the above without a
finallyis (in my opinion) somewhat less readable:*I do think a better example of
try/catch/finallyis when the exception is re-thrown (usingthrow, notthrow ex—but that’s another topic) in thecatchblock, and so thefinallyis necessary as without it code after thetry/catchwould not run. This is typically accomplished with ausingstatement on anIDisposableresource, but that’s not always the case. Sometimes the cleanup is not specifically aDisposecall (or is more than just aDisposecall).