Are there situations where it is appropriate to use a try-finally block without a catch block?
Are there situations where it is appropriate to use a try-finally block without a
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You would use it to ensure some actions occur after the
trycontent or on an exception, but when you don’t wish to consume that exception.Just to be clear, this doesn’t hide exceptions. The
finallyblock is run before the exception is propagated up the call stack.You would also inadvertently use it when you use the
usingkeyword, because this compiles into atry-finally(not an exact conversion, but for argument’s sake it is close enough).Code running in
finallyis not guaranteed to run, however the case where it isn’t guaranteed is fairly edge – I can’t even remember it. All I remember is, if you are in that case, chances are very good that not running thefinallyisn’t your biggest problem 🙂 so basically don’t sweat it.Update from Tobias:
finallywill not run if the process is killed.Update from Paddy: Conditions when finally does not execute in a .net try..finally block
The most prevalent example you may see is disposing of a database connection or external resource even if the code fails:
Compiles into something like: