Ziff Davis EnterpriseDevLife
Advertisement
Advertisement

Thursday, August 20, 2009 3:24 PM/EST

Exceptions are for Exceptional Events (and they are expensive, too)

I learned this mantra from .NET guru, Jeffrey Richter and was able to share it with a client last week.

My client had noticed a lot of messages about exceptions in the Visual Studio debug output window. However, the application was running as expected.

We decided to see where they were coming from.

First order of business was to set the debugger to break on any exception. CTRL-ALT-E brings up this window.

Then we ran the app again and the debugger did, indeed, break at the offensive line of code.

My client was running a LINQ query that used the First method. With LINQ's First method, when no results are returned, an exception is thrown.

He had the code wrapped in a try/catch statement which returned null if any problem occurred. Here is an abbreviated example of his code:

try
{
return context.Contacts.Where(c=>c.ID==somevariable);
}
catch
{
return null;
}

When the query was executed and no contact was retrieved, it was throwing an exception and the "return null" line of code was executed. That is the desired result.

However, excpetions are an expensive part of the runtime process and should not be used as a default. We can avoid the exception using the alternative FirstOrDefault method which will not throw an exception, but merely return null (or Nohting) in the case that there are no results. This matches the desired behavior of the application.

So we replaced First() with FirstOrDefault() and ran the appliation again. THe app continued to perform s expected, but we had removed the expensive exception. We did leave the exception handler in there in case some other completely unpredictable event does occur.

TrackBack

TrackBack

http://blogs.devsource.com/cgi-bin/mte/mt-tb.cgi/17728

Post a Comment

 
 

Advertisement

Syndication

Subscribe: