Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / exceptions

Logging is the new Exception Swallowing

4.00/5 (2 votes)
4 May 2011CPOL1 min read 9.4K  
Logging is the new Exception Swallowing

For a long time now, I've been stamping down hard on empty catch blocks in code, for obvious reasons. When I can dictate coding standards, that's pretty much top the list.

  1. Every 'catch' block must (at a minimum) log or throw.

    I now realize I made a mistake with this rule...it should be:

  2. Every 'catch' block must (at a minimum) throw or log.

    It's a subtle (the wording – not the formatting) difference in the way we need to think about this rule but it's one I think we don't think about enough.

For example, this is a common pattern of code that I'm seeing during Code Review sessions:

C#
public bool PerformCriticalTask()
{
    try
    {
        CriticalFunctionalityTaskA();
        CriticalFunctionalityTaskB();
        CriticalFunctionalityTaskC();
        return true;
    }
    catch(Exception ex)
    {
        Logger.Log(ex);
    }
    return false;
}
  
public CriticalFunctionalityTaskA()
{
    try
    {
        //Do Important Stuff Here
    }
    catch(Exception ex)
    {
        Logger.Log(ex);
    }
}
  
public CriticalFunctionalityTaskB()
{
    try
    {
        //Do More Important Stuff Here
    }
    catch(Exception ex)
    {
        Logger.Log(ex);
    }
}
  
public CriticalFunctionalityTaskC()
{
    try
    {
        //Do The Most Important Stuff
    }
    catch(Exception ex)
    {
        Logger.Log(ex);
    }
}

It's pretty clear that this Catch/Log pattern has become a developer's default exception handling boiler plate code. It's adding no value and actually making the troubleshooting processes more complicated and time consuming. 

My response to this is simple… remove all exception handling!

In the vast majority of cases, if an exception is thrown, the application is already broken and letting it limp along is an act of cruelty. The application should handle these critical failures as exceptional and handle all of these events the same way in an application scoped way (Custom Error Page for Web Applications, etc.). By all means, log the exception at the application scope level, it will have actual diagnostic value there (complete stack trace, etc.).

Of course, there are exceptions to this policy such as when you can legitimately recover from the fault. But these cases are few and far between.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)