Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
The Mother of Exception Handling Anti-Patterns

I know this has been discussed before elsewhere - but since I'm cranky about finding it after not-so-few-minutes of looking in some legacy code I'm working on - what follows is NOT an example of proper exception handling:

} catch (Exception ex) { AuditLogger.LogError(ex); }

This "swallow and forget" approach causes an immense amount of pain for all parties involved.  I've been working on some third party code and was troubled by the fact that the Event Viewer had a number of errors in the log, but that I hadn't encountered any blatant errors while using the application.  I only knew that every once and a while, the application didn't respond as I expected it to respond.  From a developer's perspective, this is annoying and time consuming to pin down.  From a business owner's perspective, this inconsistent behavior leads to lost business or worse.

Swallowing the exception is analogous to the "On Error Resume Next" which had many a developer (aka - me) throwing monitors out windows while debugging Active Server Pages way back when and which continues to blemish the VB.NET language.  If there's an exception, it should be assumed that something is terribly wrong; otherwise, it wouldn't be called an exception.  When exceptions occur, the application should fail and fail fast; and if that can't happen in your application (aka - a pacemaker), then careful attention should be made to ensure that exception recovery is complete, having put the application back into a state as if the exception had not occurred.

Failing fast doesn't have to mean failing ugly.  Let's face it, we write bugs in our code.  We shouldn't be embarrassed to politely let the user know that something went wrong (that it wasn't their fault), that we've been informed of the problem, and that we'll get back to them in a timely and courteous manner with a resolution.  But what we shouldn't be doing is hiding bugs under the rug and keeping our fingers crossed that the application will somehow recover on its own.  If you're lucky, the user won't notice that anything happened and will be able to continue.  But in most cases, these swallowed exceptions confuse users with erratic behavior (that's erratic application behavior, not erratic users...although they can be problematic as well) and make it hellishly difficult for developers to figure out why the application is behaving as it is.

At bare minimum, use the following as a starting point for better exception handling:

} catch (Exception ex) { AuditLogger.LogError(ex); throw; }

Note that it does not say "throw ex;"  The difference is subtle but important.  "throw ex;" re-throws the exception and overwrites the stack trace.  "throw;" simply allows the exception to pass through as if it had never been caught at all.

As I assume most of you already know this, please lean over and tap the nearest developer to you who doesn't read anything, and tell them you'll beat them with a dead chicken if you ever catch them swallowing exceptions!  (Dead chicken optional for any PETA readers out there.)

Billy McCafferty


Posted 11-30-2007 6:36 AM by Billy McCafferty
Filed under:

[Advertisement]

Comments

Pete wrote re: The Mother of Exception Handling Anti-Patterns
on 11-30-2007 3:02 PM

       public static void Main()

       {

           Form1 _form1 = new Form1();

           x:

           try

           {

               Application.Run(_form1);  

           }

           catch(Exception e)

           {

               log(e);

               goto x;

           }

       }

no more errors

Billy McCafferty wrote re: The Mother of Exception Handling Anti-Patterns
on 11-30-2007 3:09 PM

Frighteningly, that's just about what the Event Viewer log, that I was looking at, would imply!

Reddy wrote re: The Mother of Exception Handling Anti-Patterns
on 11-30-2007 3:23 PM

If developers would run FxCop analsys these kind of mistakes can be caught.

Eber Irigoyen wrote re: The Mother of Exception Handling Anti-Patterns
on 11-30-2007 4:57 PM

feeling this pain just now...

Scott’s Blog » Are Exceptions Always Errors? wrote Scott’s Blog » Are Exceptions Always Errors?
on 12-20-2007 4:57 PM

Pingback from  Scott’s Blog » Are Exceptions Always Errors?

Kay wrote re: The Mother of Exception Handling Anti-Patterns
on 01-02-2009 8:53 AM

Some people would also consider

} catch (Exception ex) {  

 AuditLogger.LogError(ex);  

 throw;  

}

To be a common anti-pattern. You should log *or* throw but not both as it leads to multiple entries in your log for the same error

Jon wrote re: The Mother of Exception Handling Anti-Patterns
on 06-12-2009 6:12 AM

Log & rethrow can be a good approach if your logging framework is reasonably sophisticated and you log more than just the exception.  For example, in a multithreaded server environment if you use some form of thread-scoped nested diagnostic context to tag errors on the same thread, and log some key variables in the method where you're logging & rethrowing, then you can process the logs to separate out the thread in question, and see the error bubbling back up through the stack, with key variables output as it goes.  This is very useful getting a handle on problems after the fact in a production environment.

Rick wrote re: The Mother of Exception Handling Anti-Patterns
on 02-23-2010 10:49 AM

Not only is that not an anti-pattern, it most definitely does not "swallow and forget".  Catching and ignoring or catching and returning null are "swallow and forget" anti patterns.

In your first example, you are explicitly logging the exception which is the opposite of forgetting. Your "solution" is the real anti-pattern referred to as "log and throw" and is actually considered the worst exception handling anti pattern.

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)