May 29

Most programmers know that throwing exceptions takes a relatively long time to execute versus normal processing.  Some say throwing exceptions is as much as two orders of magnitude slower than passing arguments (that’s 100 times slower for non-geeks).  However, another article claims there’s almost no impact to throwing exceptions, unless you are running your software in a debugger.

Exceptions Are Indeed Slower

In my ad-hoc testing using C#, I discovered that there is some truth to both of the statements above.  Outside the debugger, throwing exceptions was on average 6 times slower than passing arguments.  But inside the debugger, throwing exceptions was on average 65 times slower than passing arguments.  This was a looping test throwing an exception only one level deep, so real-life performance of exceptions multiple levels deep and scattered across a program would be even slower.

From a practical view, it’s easy to see that there is indeed extra overhead when throwing an exception.  The stack is unwound, Reflection (which itself is relatively slow) determines the stack trace and populates the properties in the exception class, there are usually memory page and hard disk cache faults as new code is loaded into memory, etc.

Exceptions Should Only Be Used for Exceptions

Therefore, exceptions should be used only to indicate a runtime error, in other words, for exceptions to normal processing (hence the name, “exception”).  Exceptions should not be used as a return type or out parameter for a method.  And exceptions should never be used to control the normal flow of execution in a program.

How Not to Use Exceptions

So Lee Dumond couldn’t believe his eyes and said “WTF!” when he saw this code in which exceptions are the primary means of passing and returning arguments.

Exceptions Rule of Thumb

I think Jon said it best:  If you ever get to the point where exceptions are significantly hurting your performance, you have problems in terms of your use of exceptions beyond just the performance.

Share and Enjoy:
  • Twitter
  • Facebook
  • Reddit
  • LinkedIn
  • Digg
  • DotNetKicks
  • StumbleUpon
  • Slashdot
  • Technorati
  • Google Bookmarks
  • Print
  • email

Article published on May 29, 2009




One Response to “Exceptions are for Exceptions”

  1. Max Says:

    I’ve run into code where exceptions are used for any type of error, even expected errors like invalid user input. You would think with the speed of computer today it really wouldn’t matter, but it still does, especially when looping or dealing with large data sets.

Leave a Reply