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?
I think the absolute answer is completely conditional (how control do you have over the environment, what is the expected balance between performance and consistency and many others I'm sure), but generally speaking I always do, choosing the safety over the potentially slower performance.
it always depend on what you want to achieve. A server not responding might be serious enough to stop all what the routine what doing, and the exception should be thrown to the caller.
In other cases, you don't care whether you failed to update the db or not. Then consuming the exception is OK.
Obviously, you don't want to show the stack trace to your end user, though, so you'll need to catch it somewhere.
That's what I found and it makes sense to me.. Check manually for the obvious things, let try-catch do the rest..
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.
Eric Lippert has a good blog on this, here.
There is no point (except for "vexing" (see blog)) catching an exception unless you can do something useful; and in most cases you simply can't - so let it bubble (your UI should obviously cleanse and display something).
You might, however, have a "try/finally" to deal with resource management. Or even cleaner, a "using" block to do the same.
I think there are three reasons to have a catch block:
- You can handle the exception and recover (from "low level" code)
- You want to rewrap the exception (again, from "low level" code)
- You're at the top of the stack, and while you can't recover the operation itself, you don't want the whole app to go down
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.