Skip to content

Instantly share code, notes, and snippets.

@JonathonReinhart
Created February 18, 2018 23:12
Show Gist options
  • Save JonathonReinhart/9e4cb8c545bd59e96761635bc25dabd8 to your computer and use it in GitHub Desktop.
Save JonathonReinhart/9e4cb8c545bd59e96761635bc25dabd8 to your computer and use it in GitHub Desktop.
Gotta catch 'em all: Last-chance exception handling in .NET with WinForms
using System;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using WinformsExceptions;
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main() {
// 4. Tell WinForms to *not use* the ThreadException handler.
// Instead, let the exceptions bubble out of the Application.Run call.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
// 3. Use AppDomain.UnhandledException to catch exceptions on *all threads*
AppDomain.CurrentDomain.UnhandledException += (sender, args) => HandleException("AppDomain.UnhandledException", (Exception)args.ExceptionObject);
// 2. Use WinForms Application.ThreadException to catch all UI thread exceptions
Application.ThreadException += (sender, args) => HandleException("Application.ThreadException", args.Exception);
// 1. Try/Catch around Application.Run
// 5. Remove the try/catch. *All Exceptions* now routed through AppDomain
try {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
catch (Exception ex) {
HandleException("try/catch around Application.Run", ex);
}
}
static void HandleException(string from, Exception ex)
{
var sb = new StringBuilder();
sb.AppendFormat("Exception on thread ID {0}, handled via {1}", Thread.CurrentThread.ManagedThreadId, from);
sb.AppendLine().AppendLine();
sb.AppendLine(ex.Message);
MessageBox.Show(sb.ToString());
Environment.Exit(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment