Search code examples
c#.netexceptionexception-logging

General Exception Handling Strategy for .NET


I’m used to having try/catch blocks in every method. The reason for this is so that I can catch every exception at the point of infraction and log it. I understand, from my reading and conversations with others, that this isn’t a popular view. One should only catch what one is prepared to handle. However, if I don’t catch at the point of infraction, then it would be possible to never log that infraction and know about it. Note: When I do catch and don’t handle, I still throw. This allows me to let the exception propagate to something that will handle it, yet still let me log it at the point of infraction.

So... How does one avoid try/catch in every method, yet still log the error at the point at which it occurred?


Solution

  • No, don't catch everything. Exceptions propagate higher up on the stack. All you have to do is make sure that the exception is caught before it gets to the top of the stack.

    This means, for instance, that you should surround the code of an event handler with a try/catch block. An event handler may be the "top of the stack". Same for a ThreadStart handler or a callback from an asynchronous method.

    You also want to catch exceptions on layer boundaries, though in that case, you might just want to wrap the exception in a layer-specific exception.

    In the case of ASP.NET, you may decide to allow ASP.NET Health Monitoring to log the exception for you.

    But you certainly don't ever need to catch exceptions in every method. That's a major anti-pattern. I would loudly object to you checking in code with that kind of exception handling.