Skip to content

Global exception handling

Context: Global exception handling catches exceptions that are not handled by application code. Different environments have different mechanisms: ASP.NET Core uses middleware, desktop applications use AppDomain.UnhandledException, and tasks use TaskScheduler.UnobservedTaskException. Global handlers are typically used for logging, displaying friendly error messages, and performing cleanup before shutdown.

using System;
class Program
{
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
{
Console.WriteLine($"Unhandled exception: {e.ExceptionObject}");
// Log and possibly shutdown gracefully
};
throw new Exception("Something went wrong!");
}
}
Terminal window
dotnet run
Unhandled exception: System.Exception: Something went wrong!
at Program.Main(String[] args)
  • Global handlers cannot prevent application termination (in most cases).
  • They are a last resort; prefer handling exceptions locally.
  • In ASP.NET Core, middleware is the recommended approach.

Desktop application – Log any unhandled exception to a file and show a user‑friendly dialog.
See .NET docs on global exception handling.