[C#] I wish I knew : catch unhandled exceptions
I’ve been a professional C# developer for years now, but I’m still discovering trivial stuffs. In “I wish I knew”, I describe a feature that I missed.
Here is a very common pattern: I’m writing an application and I want a custom dialog box to appear in case an unhandled exception occurs (and unfortunately this happens quite often ;-).
However, I don’t want this dialog to pop out when i’m debugging. I still want Visual Studio to show me the source of the exception.
My old way to do it
To do so, I used to write cumbersome codes like:
static class Program
{
static void Main()
{
#if DEBUG
MainCore();
#else
try
{
MainCore();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
#endif
}
private static void MainCore()
{
// do the actual job here
}
}
So that the try
/catch
is only compiled in the “Release” configuration.
My new way to do it
I recently discovered that you can reach the same goal with a clever use of:
AppDomain.CurrentDomain.UnhandledException
System.Diagnostics.Debugger.IsAttached
Here is the new version of the above code:
class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
// do the actual job here
}
static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached) return;
MessageBox.Show(e.ExceptionObject.ToString());
Environment.Exit(1);
}
}
I really prefer this solution for the following reasons:
- No
MainCore()
method - No
#if
- No ReSharper complaining about unused code and
using
- Works in both “Release” and “Debug” configurations
If you want to see how to do the same in Windows Forms or in WPF, see sample projects on GitHub