Tuesday, January 5, 2010

Why you should not throw Exceptions for normal Business Flow

You've heard it before and I'll tell you again, don't throw Exceptions for normal Business Logic because they are very expensive to process. It is so expensive that when you measure a return value of false verses a thrown exception, the return of false is nearly instantaneous verses a thrown exception is about 4 orders of magnitude slower.

Use booleans or other return value types to determine failure in business logic processing and only throw Exceptions when you are truly in an Exception condition.

What is an Exception condition? It's a condition where continuing to process is impossible and notification must be immediate. When you use SqlTransaction or TransactionScope, it's a quick and easy way to rollback the transaction and handle the exception in one easy step.

A great example of an Exception condition is where you retrieve data from a database and you really expected data to be there. You cannot continue processing because that data is necessary to continue.

Code:


DateTime startTime = DateTime.Now;
for (int i = 0; i < 1000; i++)
{

    try
    {
        throwException();
    }
    catch (Exception)
    {
    }

}
DateTime endTime = DateTime.Now;

Console.WriteLine("avg milliseconds for throwing: " + endTime.Subtract(startTime).TotalMilliseconds / 1000);

startTime = DateTime.Now;
for (int i = 0; i < 1000; i++)
{
    returnFalse();

}
endTime = DateTime.Now;

Console.WriteLine("avg milliseconds for returning: " + endTime.Subtract(startTime).TotalMilliseconds / 1000);

2 comments:

  1. This is such wrong advise. The whole reason to thrown an exception is that its too easy to forget to check return values. Nevermind that a method might ligitimately be allowed to return null, but might have to thrown an exception because it couldn't do its job.

    Seven seconds? Really, who cares?

    ReplyDelete
  2. The reason for exceptions is not because it is too easy to forget to check return values. Even on MSDN it states that exceptions exist so your program can communicate unexpected events to a higher execution context that is better able to recover from abnormal events.

    I should have expressed myself better that throwing an exception is 4 orders of magnitude slower than setting a return value and returning. 4 orders of magnitude on any process is a concern where any volume of transactions is involved.

    I stand firmly that exceptions are to be used for exception processing, not for normal business logic.

    Reference: http://msdn.microsoft.com/en-us/library/6dekhbbc(v=vs.80).aspx

    ReplyDelete