Exception filters in C#

Since C# 6.0, which as of writing this post has been out for about a year, we've had the option of using Exception Filters. They basically allow us to further filter what types of exceptions to handle inside a catch block, without actually entering the catch block. This last bit is very important, because the heuristic implications hereof are - I feel - often overlooked.

In this post, I'll touch on how stack unwinding works when handling exceptions, and how data is preserved or lost when exceptions are caught.

For instance, consider the following piece of code:

Let's say we have a HttpOperationException thrown as the result of an API call we previously made, and we have the above code handling it. Minor detail, the status code of the resulting operation is 404.

When looking for a handler for the exception, the runtime will find our above handler as the type matches, and enter it. As soon as a catch clause is entered, the stack is unwound. This means that any frames beyond the current method are discarded. After we've entered the catch, we find out that we can't actually handle this specific instance of the exception, so we re-throw it. At this point, we've lost all information about any variables between the original throw point and the one in the handler, making this exception harder for us to debug as we have less information available to us.

Enter exception filters. Consider the following piece of code:

Now, as soon as a handler is being searched for our HttpOperationException, the runtime will heuristically be able to tell that this handler can not handle the current instance of our exception, because the status code doesn't match.

As a result, the stack is never unwound, and the exception is passed up until either a handler for it is found, or it crashes the application. Whichever happens first, it'll have the full details regarding the exception and any variables contained in it, allowing for far easier debugging than had it been rethrown.

Keeping semantics like these in mind when writing your application can make debugging any issues you may run into far more enjoyable.

Thanks for reading!