Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

always try-catch external resource calls?

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?

like image 711
Aaron Palmer Avatar asked Oct 24 '08 11:10

Aaron Palmer


2 Answers

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.

like image 126
Pop Catalin Avatar answered Sep 21 '22 12:09

Pop Catalin


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.

like image 32
Jon Skeet Avatar answered Sep 24 '22 12:09

Jon Skeet