In this post, I mentioned that one way to use exception filters from C# code is to generate them with Reflection.Emit. Personally I usually prefer static compilation (even post-build assembly merging or rewriting) – there’s really nothing here that necessitates dynamic code generation, but I can understand the desire to avoid complicating the build process. I recently wrote up some code to do this and figured I’d share it here in case others find it useful.
There’s also a few helper methods there for common uses of exception filters. For example, to call code that you don’t expect to ever throw an exception you can just wrap it with ExecuteWithFailFast. If any exceptions escape it’ll immediately fail fast with a watson report and minidump (at the point of throw), or if a debugger is attached break at the throw point. The experience is better if running on CLR v4 – it makes use of the new FailFast API that takes an exception (eg. this will cause the debugger to break with the exception assistant, just as if the exception had gone unhandled). For example you can use this as follows:
Sometimes it’s useful to be able to catch multiple distinct exception types with the same catch block (without unwinding the stack for other exceptions, so unexpected exceptions are easier to debug live or in a dump file). Here are two examples:
And here’s an example of a general-purpose exception filter:
Again, there are good reasons why C# doesn’t support exception filters directly. But there are a few cases where they can be really invaluable. I hope you find this useful.