Handling Unhandled Exceptions

An unhandled exception is one that propagates up the call stack without being caught by an exception handler in a catch block.  By default, the .NET runtime will cause a dialog to be displayed when an unhandled exception occurs.
908-001
When an unhandled exception occurs, you can’t recover from the exception.  But you can do some final logging and then terminate the application quietly by adding a handler to the AppDomain.UnhandledException event.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
static void Main(string[] args)
{
    // Specify handler for all unhandled exceptions
    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
 
    throw new ApplicationException("Something bad happened");
 
    Console.ReadLine();
}
 
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    Exception theException = (Exception)e.ExceptionObject;
 
    Console.WriteLine("- In the unhandled exception handler -");
    Console.WriteLine(theException.ToString());
 
    // Exit to avoid unhandled exception dialog
    <span class="skimlinks-unlinked">Environment.Exit(-1</span>);
}
908-002