Tags: , | Categories: Programming Posted by mharman on 12/27/2010 4:43 PM | Comments (0)

I was about to write another blog post when I realized that I never posted the results of the survey. Thanks to all who participated.

Question: When is it appropriate to use a Try/Catch (or equivalent) code block?

Answers (responses/percentage):

  1. never use them -- 0/0%
  2. wrap code that has had a problem -- 1/3.7%
  3. wrap code that makes external function calls -- 19/70.4%
  4. wrap code that I'm unsure of -- 4/14.8%
  5. wrap almost all code in a try/catch -- 1/3.7%
  6. other (please specify) -- 2/7.4%

 

I use try/catch around code that - quite reasonably and outwith the control of my software - might fail. I usually rethrow an exception anyhow, but an exception type & message specific to my application.

For example a user-managed XML file might become invalid due to being malformed or not passing validation. I would not let the XML parser's own exception to bubble up, I'd catch it and raise my own "you have borked you XML file" exception.

I do *not* use try catch to hide or ignore errors (or set "failed" status flags: bleah), I use them to tune them to my requirement or the situation at hand.


I normally put try/catches around webservice calls such as facebook, in case the response takes to long, otherwise on heavily hit sections of a website where there is a greater chance of a sql deadlock error