3

What is the best practice for handling exceptions without having to put try/catch blocks everywhere?

I had the idea of creating a class that is devoted to receiving and handling exceptions, but I am wondering if its a good design idea. Such a class would receive an exception and then decide what to do with it depending on its type or error code, could even parse the stack trace for specific information, etc.

Here is the basic idea behind and implementation:

public class ExceptionHandler
{
    public static void Handle(Exception e)
    {
        if (e.GetBaseException().GetType() == typeof(ArgumentException))
        {
            Console.WriteLine("You caught an ArgumentException.");
        }
        else
        {
            Console.WriteLine("You did not catch an exception."); 
            throw e;   // re-throwing is the default behavior
        }
    }
}

public static class ExceptionThrower
{
    public static void TriggerException(bool isTrigger)
    {
        if (isTrigger)
            throw new ArgumentException("You threw an exception.");
        else
            Console.WriteLine("You did not throw an exception."); 
    }
}

class Program
{
    static void Main(string[] args)
    {
        try
        {
            ExceptionThrower.TriggerException(true); 
        }
        catch(Exception e)
        {
            ExceptionHandler.Handle(e);  
        }
        Console.ReadLine(); 
    }
}

I thought this would be an interesting endeavor because you would theoretically only need one or very few try / catch blocks around your main() method calls, and let the exception class handle everything else including re-throwing, handling, logging, whatever.

Thoughts?

4
  • 1
    By re-throwing the exception in your ExceptionHandler class, you will lose the previous stack-trace. Apr 6, 2011 at 22:45
  • Is there a way to preserve the stack trace? Apr 6, 2011 at 22:52
  • 2
    replace throw e; with throw; Apr 6, 2011 at 22:53
  • Rather than throwing in ExceptionHandler, you could return a bool for whether the Exception was handled or not. If not, "throw;" from the original code. However, I'm not sure this is a good design in general. Apr 6, 2011 at 22:57

4 Answers 4

6

There is actually a good reason why you don't see similar designs in production code.

First of all, such a design cannot help you reduce the count of try/catch pairs in your code (this should be obvious). It could help you reduce the number of catch statements for a given try, since you could just catch System.Exception and forward to the ExceptionHandler...

But what next?

Every exception needs to be handled differently. How would the ExceptionHandler know exactly what to do? You could try to solve this in a number of ways, e.g.:

  1. Derive from ExceptionHandler and put the code to handle exceptions in virtual methods
  2. Pass a number of Action<Exception> instances to the handler and have it invoke the proper one

Solution (1) would be worse than what you had before: now you need to create a whole new class for each try block and override a bunch of methods to end up with something worse than you had before (it's not immediately clear how the code in a particular class fits in the flow of your program). It would also leave another important question unanswered: you may need context (access to variables in the current scope) to properly handle the exception. How will you provide access to this context?

Solution (2) would actually end up quite similar to writing the catch blocks that we 've been wanting to avoid (each Action would be effectively the contents of a catch block). We end up doing the same thing, only in a more complicated and verbose manner.

There are also other issues:

  • What should ExceptionHandler do if it cannot handle the exception? Throwing it again will cause you to lose the original stack trace, in effect destroying all the good information in there.
  • What if there's a bug in ExceptionHandler? You can truse a try/catch. Can you trust code you wrote yourself to the same degree?

As for the ExceptionThrower... what benefit could it possibly offer over throw new Exception();?

Exception handling is a complicated matter already, and it's difficult enough to get it right without adding extra gears to the machine. Especially if they don't buy you anything new. Don't do it.

6
  • Take a simple console app for example -- If I have a line of code in my Main() method that executes the UI, and wrap try catch around that, wont any exception that occurs in the application bubble up to that catch block? Or am I missing something? Why would I need more than that single try/catch? Apr 6, 2011 at 22:54
  • 2
    @SeanThoman: Because there are exceptions you can reasonably expect (e.g. trying to open a file you might get a FileNotFoundException) and exceptions that mean game over for the whole process (e.g. ExecutionEngineException). You cannot reasonably respond to both from the same place; you need different context.
    – Jon
    Apr 6, 2011 at 22:59
  • I think you could by just configuring the logic of the handling class, but it may be too complex, and introduce its own bugs as you mentioned. What if this were a non-UI based app though, would that make this more feasible as a solution? Just a worker app executing some processes in sequence, totally hands off, where an administrator would just be checking logs periodically to ensure things are going along smoothly. You don't want the app to stop running for certain exceptions, etc. Apr 6, 2011 at 23:07
  • @SeanThoman: Stop thinking about if it might work for a second and think what does it buy you that you can't already do? It's easy to "make something work" in a 10-line example. But as a general-use tool, which you would naturally want to utilize in a large application, this would add to your problems instead of reducing them.
    – Jon
    Apr 6, 2011 at 23:12
  • Alright, pretty new to this, appreciate it! I see your points. The pros I considered is that it would allow you to configure your exception handling precisely in one place. You could modify the logic of exception handling within a fairly decoupled component. But maybe these 'pros' if they even are pros are outweighted by the cons. Apr 6, 2011 at 23:23
6

OK, this is probably not the answer you want but...

I am generally allergic towards the idea of a general exception handling class. You can almost hear how it is a contradiction in itself. An exception is an exceptional event. Exceptional events cannot be handled in a general manner, but needs tailored handling wherever they may appear, which essentially means that your code should to two things:

  1. be defensive about any input in order to avoid exceptions in the first place
  2. put try..catch blocks wherever it makes sense to catch and handle an exception (note that this means that you should not have try..catch blocks in all methods)

So, where does it make sense to catch and handle an exception? In short, where your code has knowledge that makes it capable of handling the exception. If it does not, let the exception bubble upwards to the caller. The only place where I think you should catch all exceptions and have some generic default behavior around what to do, it at the top level of your app. That is typically the UI.

1

Sorry, this is not a good idea. When you catch an exception in your code with a normal try/catch block surrounding the relevant section, you get to use two critical pieces of information to deal with the problem: the type of exception, and also where the exception occured.

With your arrangement, you have to deal with all exceptions knowing only what type of exceptions they are. You no longer know where the exception actually occured, so you really can't do anything about the problem other than to log it or show a message to the user.

Moreover, try/catch blocks often also include a finally block, in which you can make sure things happen even if an exception is thrown (like closing streams etc.). You don't have any way in your arrangement of dealing with this.

Proper exception handling can be tricky, and there is no magic bullet that will make it simple and straightforward. If there were, .Net would have already incorporated it.

2
  • You could know where it occured by using the stack trace...but I do see your point. Since using 'throw e' destroys the stack trace, and using just 'throw' is only allowed in a catch block, it seems tricky..you'd have to log the stack trace or programmtically do something with the stack trace before 'throw e'. Apr 6, 2011 at 23:00
  • You mean if you wrote a stack trace parser (yay!) you could deduce where the exception occured. True, but then you still need to put code somewhere in order to respond appropriately to the particular exception type and location info. Why not put this in a normal catch block, right below the code that's causing the problem? Apr 6, 2011 at 23:05
1

We have a class in our code-base that has a pretty similar signature to the one you have proposed and I can tell you now that it has only bough misery and suffering!

Why do you have so many try-catch blocks in your code? Can you give some examples? Exceptions by their very nature "Exceptional", i.e.not that frequent! Not only should you not be catching exceptions that frequently, but also every exception is different and the same boilerplate code that works in one situation probably isn't suitable in many other situations.

Nobody said that exception handling was easy (or produced compact code) - you should think carefully about each situation you need to catch an exception and handle it appropriately - avoid catching exceptions that you don't need to handle.

1
  • I dont actually have that many try catch blocks ... but I was curious about the idea. Apr 6, 2011 at 23:05

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.