Catching Unhandled Errors in .NET/C++

Most developers are familiar with the pain that comes from an application crashing in production, and not offering any helpful information why it crashed. I recently was tasked with trying to catch some mystery errors, and I learned a lot about how .NET has some built in tools to catch errors in C++.

The SetUnhandledExceptionFilter function supersedes the top-level exception handler in a thread, so if you hit an error the function will catch and allow you to do something before everything goes up in flames. This is a great time to do things like creating logs that will give some insight about what went wrong. It'll allow you to get a better idea of why a program crashes in production. Keep in mind, this only works outside of the debugger, so even in Visual Studio you'll need to run without debugging to test this.

This code snippet is probably the simplest proof of concept for this tool that I could come up with. Essentially we are going to set the function that will handle our unhandled exceptions and then when we reach an exception that function will trigger, causing a simple message that prints to a file. In a real environment you may consider printing a stack trace or return the name of the function where the error came from.

The AddVectoredExceptionHandler function is a similar way to handle errors. It takes two parameters instead of one, the first being the order in which the handler is called. If you have some other error handling in your system that is maybe hiding your SetUnhandledExceptionFilter, try setting this function to 0 so it's called first.

Comments

Popular posts from this blog

Reviewing WPF and MVVM

Using WebRTC to build a videophone in React and TypeScript

Learning Flutter