Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Exceptions and Diagnostics

Unhandled exceptions

Reference for unhandled exceptions in C#: what happens when nothing catches, AppDomain.UnhandledException, FirstChanceException and UnobservedTaskException.

An exception is unhandled when no catch block on the call stack matches it. In a .NET application that ends the process: the runtime reports the exception (to the console, the Windows event log or a crash dump) and exits with a failure code. Which thread threw does not matter; an unhandled exception on any thread ends the whole process.

You cannot turn that into a recovery, but you can observe it. AppDomain.CurrentDomain.UnhandledException runs just before termination so you can write a last log entry. AppDomain.CurrentDomain.FirstChanceException fires for every thrown exception, even handled ones, and TaskScheduler.UnobservedTaskException reports faulted tasks that nobody awaited.

C#
AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
    Console.Error.WriteLine("fatal: " + ((Exception)args.ExceptionObject).Message);
};

Try it

C# FirstChanceException sees handled exceptions too

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# The handler runs, then the process ends

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
event UnhandledExceptionEventHandler? AppDomain.UnhandledException;
event EventHandler<FirstChanceExceptionEventArgs>? AppDomain.FirstChanceException;
static event EventHandler<UnobservedTaskExceptionEventArgs>? TaskScheduler.UnobservedTaskException;

public class UnhandledExceptionEventArgs : EventArgs
{
    public object ExceptionObject { get; }
    public bool IsTerminating { get; }
}
Member Description
UnhandledException Raised for an exception no handler caught. ExceptionObject is usually an Exception; cast carefully.
IsTerminating true when the runtime will end the process after the handlers run.
FirstChanceException Raised when an exception is thrown, before the runtime looks for a handler. Handlers must not throw.
UnobservedTaskException Raised on the finalizer thread for a faulted task whose exception was never observed. Call args.SetObserved() to mark it seen.

Errors / undefined behavior: an exception thrown from an UnhandledException handler does not help; the process is already ending. A FirstChanceException handler that throws or allocates heavily can recurse; keep it tiny.

Usage notes

  • The handler cannot save the process. It is for logging, flushing buffers and showing a message. State may be corrupt, so do not continue normal work.
  • Output is not guaranteed after the handler. The runtime then writes its own report and exits with a non-zero code. In the second example the runtime prints the exception and a trace to the error stream after the handler's lines, then the process is killed (the runner reports it as an abort).
  • Hosts install their own handlers. ASP.NET Core catches exceptions per request and turns them into 500 responses; Generic Host background services stop the host by default (BackgroundServiceExceptionBehavior.StopHost).
  • UI frameworks have extra events, for example Application.DispatcherUnhandledException in WPF. Those events can mark an exception handled; the AppDomain one cannot.
  • async void is the usual surprise. An exception that escapes an async void method is raised on the synchronization context and can crash the app. Use async Task.
  • Unobserved tasks no longer crash the process (since .NET 4.5). The event fires after garbage collection, so timing is not predictable.
  • FirstChanceException is noisy. Programs throw and catch exceptions routinely, so use it for diagnostics and tooling, not for business logic.
  • Wrap Main for friendly errors. A top-level try/catch that logs and returns an exit code is clearer than relying on the event.