Click here to Skip to main content
11,709,366 members (51,605 online)
Click here to Skip to main content

Do NOT catch that exception!

, 1 Mar 2013 LGPL3 34.2K 44
Rate this:
Please Sign up or sign in to vote.
Ohhh, I've recently seen one to many application where the developers try to be safe by catching exceptions all over the place. It can be everything from a small simple method that doesn't throw that many exceptions to a large method with multiple try/catch statements. Most of those catch blocks jus

Ohhh, I’ve recently seen one to many application where the developers try to be safe by catching exceptions all over the place. It can be everything from a small simple method that doesn’t throw that many exceptions to a large method with multiple try/catch statements. Most of those catch blocks just logs the exception and rethrow it.

Please do not catch that exception. Let it travel down the call stack. I promise you that you won’t regret it. You’ll get a warm and fuzzy feeling next time you’ll test your application. I promise you! Really!

Why? You’ll get a complete exception with all the details you need to fix the error. The problem with all of those try/catch blocks is they doesn’t help your application in any way. They just clutter up the code and your log files.

If you still want to catch exceptions: I’ll try to explain the way to do it.

Catching exceptions in the correct way.

Yeah. Proper exception handling can be something wonderful. You’ll smile every time you get an exception. First of all: Exceptions only happens when something exceptional occurs. Please have that in mind, because it helps you remember that you don’t need those try/catch block everywhere. That brings us to the golden rule about when to catch exceptions:

Only catch exceptions that you can handle to rescue the situation.

You should only catch exceptions if you can deliver the result as promised by the method contract. For instance, if the return value from a method is an User object, you should only catch an exception if you in fact can return a User.

Anything else is not really exception handling but just diagnostics.

There are of course exceptions, namely two of them:

Do not let layer specific exceptions propagate up the call stack.

For instance, if the data layer fails and throws a SqlException (if you are using Sql Server) you should catch it and wrap it inside a more generic exception. For instance: Create a DataSourceException which could be used even if you switch data source from a database to a Web Service. You should of course add details to the exception such as the method in your data layer that failed (let’s say “SearchUsers”) and the arguments for that method. Do NOT forget to add the original exception as inner exception.

public class UserRepository : IUserRepository
{
    public IList<User> Search(string value)
    {
        try
        {
              return CreateConnectionAndACommandAndReturnAList(
                 "WHERE value=@value", Parameter.New("value", value));
        }
        catch (SqlException err)
        {
             var msg = String.Format(
                 "Ohh no!  Something failed when you tried to search after users" +
                 "with '{0}' as search string", value);
             throw new DataSourceException(msg, err);
        }
    }
}

Update 2013-03-01: I'm not following this rule any more. The only time I wrap exceptions is if I add more context information to help me prevent the exception in the future. It doesn't really matter if the data layer exception is passed up the call stack, since it won't be handled but just logged in the top layer.

If you don't want to display data layer specific information to the user, then simply display something like "An unexpected error occurred" instead of showing exception information. The exception information doesn't really help your user either way.

Try/Catch all is OK in the layer closest to the user.

Ok, so you have let the exceptions propagate through all your layers to the presentation layer (winforms/asp.net etc). Fine. Go ahead, give the user some fancy error pages. Also log those errors. But just don’t log them. Notify a support team. Send an email to the project lead.

When everything else fails

Are you not sure that your new exception policy will catch all of those exceptions? Is it scary? The I got the solution for YOU!

  • Asp.Net: Implement Aplication_OnError(object source, EventArgs e) in your global.asa. It will be called for all unhandled exceptions.
  • Winforms: Subscribe on Application.ThreadException
  • Winservices/console apps: Subscribe on AppDomain.CurrentDomain.UnhandledException. The problem with this event is that it will still terminate the application. But there’s a way around that too
  • WCF: Implement IErrorHandler and log the exceptions in it (added 2013-03-01)
  • ASMX: Create a custom Soap Extension. (added 2013-03-01)

In the next blog post I’ll discuss common mistakes in those catch blocks and how your tailor made exceptions should look like.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)

Share

About the Author

jgauffin
Founder Gauffin Interactive AB
Sweden Sweden
Founder of OneTrueError, a .NET service which captures, analyzes and provide possible solutions for exceptions.

blog | twitter

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Jasmine25014-Mar-13 12:33
memberJasmine25014-Mar-13 12:33 
GeneralRe: My vote of 5 Pin
Jasmine25014-Mar-13 12:34
memberJasmine25014-Mar-13 12:34 
GeneralRe: My vote of 5 Pin
jgauffin4-Mar-13 22:19
memberjgauffin4-Mar-13 22:19 
GeneralRe: My vote of 5 Pin
Jasmine25015-Mar-13 5:12
memberJasmine25015-Mar-13 5:12 
GeneralMy vote of 5 Pin
Robert Hoffmann2-Mar-13 4:47
memberRobert Hoffmann2-Mar-13 4:47 
GeneralMy vote of 5 Pin
jahmani1-Mar-13 10:20
memberjahmani1-Mar-13 10:20 
QuestionGood article, but exceptions are all about how the solution should behave. Pin
egilagre3-Dec-12 2:39
memberegilagre3-Dec-12 2:39 
QuestionFinally Pin
pip0106-Nov-12 2:13
memberpip0106-Nov-12 2:13 
AnswerRe: Finally Pin
jgauffin6-Nov-12 2:16
memberjgauffin6-Nov-12 2:16 
GeneralRe: Finally Pin
pip0106-Nov-12 4:43
memberpip0106-Nov-12 4:43 
GeneralRe: Finally Pin
jgauffin6-Nov-12 4:46
memberjgauffin6-Nov-12 4:46 
GeneralRe: Finally Pin
pip0106-Nov-12 4:57
memberpip0106-Nov-12 4:57 
GeneralRe: Finally Pin
Jasmine25014-Mar-13 8:48
memberJasmine25014-Mar-13 8:48 
GeneralRe: Finally Pin
pip0104-Mar-13 23:14
memberpip0104-Mar-13 23:14 
GeneralNice Pin
Zac Greve9-Sep-12 8:04
memberZac Greve9-Sep-12 8:04 
GeneralTotally agree with you but... Pin
Lokanta_brahmachari18-Nov-10 3:56
memberLokanta_brahmachari18-Nov-10 3:56 
GeneralRe: Totally agree with you but... Pin
jgauffin20-Nov-10 9:37
memberjgauffin20-Nov-10 9:37 
GeneralRe: Totally agree with you but... Pin
pip0106-Nov-12 4:39
memberpip0106-Nov-12 4:39 
GeneralFor vb.net: Capture information about exceptions without catching them Pin
supercat915-Nov-10 7:05
membersupercat915-Nov-10 7:05 
GeneralRe: For vb.net: Capture information about exceptions without catching them Pin
jgauffin15-Nov-10 21:40
memberjgauffin15-Nov-10 21:40 
GeneralMy vote of 5 Pin
thatraja9-Nov-10 19:50
memberthatraja9-Nov-10 19:50 
GeneralGood article.... Pin
GlimmerMan9-Nov-10 5:03
memberGlimmerMan9-Nov-10 5:03 
Generalexcelent article Pin
Split_fire8-Nov-10 21:44
memberSplit_fire8-Nov-10 21:44 
General5-5 Pin
erick.granados8-Nov-10 17:35
membererick.granados8-Nov-10 17:35 
GeneralGreat advice Pin
CurtainDog8-Nov-10 12:39
memberCurtainDog8-Nov-10 12:39 
GeneralRe: Great advice Pin
jgauffin8-Nov-10 20:06
memberjgauffin8-Nov-10 20:06 
GeneralRe: Great advice Pin
pip0106-Nov-12 4:47
memberpip0106-Nov-12 4:47 
GeneralRe: Great advice Pin
Jasmine25014-Mar-13 8:52
memberJasmine25014-Mar-13 8:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150819.1 | Last Updated 1 Mar 2013
Article Copyright 2010 by jgauffin
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid