6

I am working on a fairly complex .NET application that interacts with another application. Many single-line statements are possible culprits for throwing an Exception and there is often nothing I can do to check the state before executing them to prevent these Exceptions.

The question is, based on best practices and seasoned experience, how frequently should I lace my code with try/catch blocks? I've listed three examples below, but I'm open to any advice.

I'm really hoping to get some pros/cons of various approaches. I can certainly come up with some of my own (greater log granularity for the O-C approach, better performance for the Monolithic approach), so I'm looking for experience over opinion.


EDIT: I should add that this application is a batch program. The only "recovery" necessary in most cases is to log the error, clean up gracefully, and quit. So this could be seen to be as much a question of log granularity as exception handling. In my mind's eye I can imagine good reasons for both, so I'm looking for some general advice to help me find an appropriate balance.


Monolitich Approach

class Program{
    public static void Main(){
        try{
            Step1();
            Step2();
            Step3();
        } catch (Exception e) {
            Log(e);
        } finally {
            CleanUp();
        }
    }

    public static void Step1(){
        ExternalApp.Dangerous1();
        ExternalApp.Dangerous2();
    }

    public static void Step2(){
        ExternalApp.Dangerous3();
        ExternalApp.Dangerous4();
    }

    public static void Step3(){
        ExternalApp.Dangerous5();
        ExternalApp.Dangerous6();
    }
}

Delegated Approach

class Program{
    public static void Main(){
        try{
            Step1();
            Step2();
            Step3();
        } finally {
            CleanUp();
        }
    }

    public static void Step1(){
        try{
            ExternalApp.Dangerous1();
            ExternalApp.Dangerous2();
        } catch (Exception e) {
            Log(e);
            throw;
        }
    }

    public static void Step2(){
        try{
            ExternalApp.Dangerous3();
            ExternalApp.Dangerous4();
        } catch (Exception e) {
            Log(e);
            throw;
        }
    }

    public static void Step3(){
        try{
            ExternalApp.Dangerous5();
            ExternalApp.Dangerous6();
        } catch (Exception e) {
            Log(e);
            throw;
        }
    }
}

Obsessive-Compulsive Approach

class Program{
    public static void Main(){
        try{
            Step1();
            Step2();
            Step3();
        } finally {
            CleanUp();
        }
    }

    public static void Step1(){
        try{
            ExternalApp.Dangerous1();
        } catch (Exception e) {
            Log(e);
            throw;
        }
        try{
            ExternalApp.Dangerous2();
        } catch (Exception e) {
            Log(e);
            throw;
        }
    }

    public static void Step2(){
        try{
            ExternalApp.Dangerous3();
        } catch (Exception e) {
            Log(e);
            throw;
        }
        try{
            ExternalApp.Dangerous4();
        } catch (Exception e) {
            Log(e);
            throw;
        }
    }

    public static void Step3(){
        try{
            ExternalApp.Dangerous5();
        } catch (Exception e) {
            Log(e);
            throw;
        }
        try{
            ExternalApp.Dangerous6();
        } catch (Exception e) {
            Log(e);
            throw;
        }
    }
}

Other approaches welcomed and encouraged. Above are examples only.

5
  • Also, for what it's worth, I've read through the Best Practices for Handling Exceptions on the MSDN website. It did not address this question.
    – JDB
    Nov 2, 2012 at 18:48
  • 2
    Don't throw e; it resets the stack trace. Do throw; instead. Nov 2, 2012 at 18:48
  • @RobertHarvey - Thanks for the advice. Edited question to bring focus back to the main topic. :)
    – JDB
    Nov 2, 2012 at 18:51
  • Do you really have to log the exceptions individually here, or can you just catch them all in one place higher up in the call stack and log them there? Nov 2, 2012 at 18:51
  • I've probably used the first two examples at some point tbh, all depending on the responisbility and expectations of the method. I don't know if I've used the third option that much. Seems a bit messy to me??
    – dreza
    Nov 2, 2012 at 18:54

3 Answers 3

12

Catch at the granularity that is meaningful to your application. If you are not going to take a different action for a different exception source, then there is no need to break those things apart.

3
  • Edited the question - in your experience, what level of log granularity is the most helpful? Is it meaningful to log different messages in different contexts, or is that something you can get from looking over the code. (Obviously, I'm looking for the most general advice.)
    – JDB
    Nov 2, 2012 at 19:17
  • In my experience the most valuable things in the log are the stack trace, exception type, and error message (should the exception thrower be so kind as to provide that). The next nicest thing to have would be the parameter values that the current method received. In many domains logging that data is a no-no ("Employee: Rob Robson, Salary: $10,000" can annoy people). It helps to have nice, short methods that you can trace through. (Edit: The stack trace tells you where the error is thrown, so you can catch at a high level and still have fine grained information about error source)
    – Ben
    Nov 2, 2012 at 19:36
  • @Cyborgx37 while I agree that some things are pretty valuable often times as Ben has listed, but I have to chime in and press against logging anything beyond the absolute minimum you'll need, and say, DO: add artifacts after you run into needing them and ONLY: log those particular things in those particular places. Just to explain, I have worked on a few instrumentation systems and the biggest problem they run into is information overload, and the information not being stored in a structured manner. Either of these 2 things can make the data truly unusable. Nov 3, 2012 at 1:50
4

I favor approach one.

The exceptions are going to go up the call stack to the try/catch block in the main method, and get logged there anyway.

Don't catch in your step methods unless you can handle each exception locally somehow.

3
  • 2
    Just to add to this, it also matters if you want the steps to continue or not. In Step1 there's two calls. If you want/need the second call to occur even if the first one causes an exception (though I would caution against wanting that), then that's a reason to catch lower. Otherwise I agree with this, +1
    – Telastyn
    Nov 2, 2012 at 19:07
  • Edited the question to provide a bit more background, but essentially there is no recovery from any Exception other than to log it and quit. So this question also has to do with log granularity. In your experience, does it help to have more specialized, detailed logs, or just a general log message followed by detailed analysis?
    – JDB
    Nov 2, 2012 at 19:19
  • 1
    @Cyborgx37 once you have a stacktrace from the exception source, that's all that really matters. Personally, I would favor DRY and just catch in Main. Cluttered code leads to crappy code.
    – Telastyn
    Nov 2, 2012 at 19:31
3

Ask yourself why exception syntax was invented when it's perfectly possible to handle unexpected conditions without them. In C, all code looks like your obsessive-compulsive approach, except for instead of a try/catch block, the return value of the function indicates success or failure.

The reason exceptions were invented is to allow code to look like your monolithic approach. It's much cleaner, follows the DRY principle, and it's easier to have people write the lower layers without imposing strict rules on exception handling in every single function. That should be your default mode of operation, and you should only also catch exceptions at the lower layers if you can actually recover from the error, not just report it.

1
  • I'd generally agree, but there are often state values that are reportable from a lower level that are not visible to a higher level. So, as my edited question now includes, this is as much a question about the value of a specific log over a general log, and advice for finding a good balance.
    – JDB
    Nov 2, 2012 at 19:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.