I understand how try-catch works and how try-finally works, but I find myself using those (usually) in two completely different scenarios:
- try-finally (or
using
in C# and VB) is mostly used around some medium-sized code block that uses some resource that needs to be disposed properly. - try-catch is mostly used either
- around a single statement that can fail in a very specific way or
- (as a catch-all) at a very high level of the application, usually directly below some user interface action.
In my experience, cases where a try-catch-finally would be appropriate, i.e., where the block in which I want to catch some particular exception is exactly the same block in which I use some disposable resource, are extremely rare. Yet, the language designers of C#, VB and Java seem to consider this to be a highly common scenario; the VB designers even think about adding catch to using
.
Am I missing something? Or am I just overly pedantic with my restrictive use of try-catch?
EDIT: To clarify: My code usually looks like this (functions unrolled for clarity):
Try
do something
Aquire Resource (e.g. get DB connection)
Try
do something
Try
do something that can fail
Catch SomeException
handle expected error
do something else...
Finally
Close Resource (e.g. close DB connection)
do something
Catch all
handle unexpected errors
which just seems to make much more sense than putting any of the two catches on the same level as finally just to avoid indentation.