Should I always wrap external resource calls in a try-catch? (ie. calls to a database or file system) Is there a best practice for error handling when calling external resources?
Catch only exceptions that you can handle. So for example when using external resources, the best practice is to catch specific exceptions that you know you can handle. In case of files this can be (IOException, SecurityException, etc), in case of Database the exception can be SqlException or others.
In any case, don't catch exceptions that you don't handle, let them flow to a upper layer that can. Or if for some reason you do catch exceptions but don't handle them, rethrow them using just throw; (which will create an rethrow IL op, as opposed to trow).
In case of using resources that you don't know what type of exceptions might throw, you are kind of forced to catch the general exception type. And in this case the safes thing would be to use the said resources from a different app domain (if possible), or let the exception bubble up to top level (ex UI) where they can be displayed or logged.
I think there are three reasons to have a catch block:
If you stick to these, you should have very few catch blocks compared with try/finally
blocks - and those try/finally
blocks are almost always just calling Dispose
, and therefore best written as using
statements.
Bottom line: It's very important to have a finally
block to free resources, but catch
blocks should usually be rarer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With