SYSK 362: The cost of try/catch

Since I’m still coming across a lot of conflicting recommendations on the “best practices for structure exception handling” (including those coming from different folks from Microsoft), I decided to write a blog post on the topic.

 

So, what are the benefits and costs with SEH?

 

Let me first address the cost of adding try/catch/finally…

 

John Lee (a peer MCS consultant) did some profiling on his HP Compaq nc8430 Laptop (Dual Core CPU 2.16GHz, 4GB RAM) and, using that hardware, the approximate overhead of adding try/catch per function when exception is not thrown is 0.00001235 ms. In comparison, getting a connection from a connection pool takes 0.0409662 ms => over 3,000 times slower. If an exception is thrown from a function nested 10 levels deep with try/catch and rethrow at every level, then the execution time goes up to 0.02010861 ms.

 

Using the numbers above, in my opinion, the cost of try/catch (especially given that, in most cases, the code runs successfully without incurring the cost of throwing an exception) in the context of creating business applications (I’m not talking about critical, real-time or near real time apps which most likely are not written in .NET anyway), is so negligible that the benefits (see next paragraph) far outweigh the cost.

 

As to the benefits… In my projects, in addition to the standard call stack info, I add the actual data passed to each function in the faulting call stack to the exception message eventually logged to a database. In most cases, this gives me sufficient data to recreate the problem and do root cause analysis in a fraction of the time it would take without such details.

 

In summary, if a method can either handle the exception (e.g. correct the problem and/or retry) or has other value-add (e.g. log passed in parameter values in the catch block), then the value of sprinkling the try/catch in every single method (not just at the top-most level) in business level applications is significantly greater, in my opinion, then the cost of the try/catch statements.

 

 

Special thanks to John Lee for doing the profiling!