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?
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:
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.