AppDomain.FirstChanceException Event

Occurs when an exception is thrown in managed code, before the runtime searches the call stack for an exception handler in the application domain.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

public event EventHandler<FirstChanceExceptionEventArgs> FirstChanceException

This event is only a notification. Handling this event does not handle the exception or affect subsequent exception handling in any way. After the event has been raised and event handlers have been invoked, the common language runtime (CLR) begins to search for a handler for the exception. FirstChanceException provides the application domain with a first chance to examine any managed exception.

The event can be handled per application domain. If a thread passes through multiple application domains while executing a call, the event is raised in each application domain that has registered an event handler, before the CLR begins searching for a matching exception handler in that application domain. After the event has been handled, a search is made for a matching exception handler in that application domain. If none is found, the event is raised in the next application domain.

You must handle all exceptions that occur in the event handler for the FirstChanceException event. Otherwise, FirstChanceException is raised recursively. This could result in a stack overflow and termination of the application. We recommend that you implement event handlers for this event as constrained execution regions (CERs), to keep infrastructure-related exceptions such as out-of-memory or stack overflow from affecting the virtual machine while the exception notification is being processed.

This event is not raised for exceptions that indicate corruption of process state, such as access violations, unless the event handler is security-critical and has the HandleProcessCorruptedStateExceptionsAttribute attribute.

The common language runtime suspends thread aborts while this notification event is being handled.

The following example creates a series of application domains named AD0 through AD3, with a Worker object in each application domain. Each Worker object has a reference to the Worker object in the next application domain, except for the Worker in the last application domain. The FirstChanceException event is handled in all application domains except AD1.

NoteNote

In addition to this example, which demonstrates first-chance exception notifications in multiple application domains, you can find simple use cases in How to: Receive First-Chance Exception Notifications.

When the application domains have been created, the default application domain calls the TestException method for the first application domain. Each Worker object calls the TestException method for the next application domain, until the last Worker throws an exception that is either handled or unhandled. Thus, the current thread passes through all the application domains, and TestException is added to the stack in each application domain.

When the last Worker object handles the exception, the FirstChanceException event is raised only in the last application domain. The other application domains never get a chance to handle the exception, so the event is not raised.

When the last Worker object does not handle the exception, the FirstChanceException event is raised in each application domain that has an event handler. After each event handler has finished, the stack continues to unwind until the exception is caught by the default application domain.

NoteNote

To see how the stack display grows as the event is raised closer and closer to the default application domain, change e.Exception.Message to e.Exception in the FirstChanceHandler event handlers. Notice that when TestException is called across application domain boundaries, it appears twice: once for the proxy and once for the stub.

using System;
using System.Reflection;
using System.Runtime.ExceptionServices;

class Example
{
    static void Main()
    {
        AppDomain.CurrentDomain.FirstChanceException += FirstChanceHandler;

        // Create a set of application domains, with a Worker object in each one. 
        // Each Worker object creates the next application domain.
        AppDomain ad = AppDomain.CreateDomain("AD0");
        Worker w = (Worker) ad.CreateInstanceAndUnwrap(
                                typeof(Worker).Assembly.FullName, "Worker");
        w.Initialize(0, 3);

        Console.WriteLine("\r\nThe last application domain throws an exception and catches it:");
        Console.WriteLine();
        w.TestException(true);

        try
        {
            Console.WriteLine(
                "\r\nThe last application domain throws an exception and does not catch it:");
            Console.WriteLine();
            w.TestException(false);
        }
        catch (ArgumentException ex)
        {
            Console.WriteLine("ArgumentException caught in {0}: {1}", 
                AppDomain.CurrentDomain.FriendlyName, ex.Message);
        }
    }

    static void FirstChanceHandler(object source, FirstChanceExceptionEventArgs e)
    {
        Console.WriteLine("FirstChanceException event raised in {0}: {1}",
            AppDomain.CurrentDomain.FriendlyName, e.Exception.Message);
    }
}

public class Worker : MarshalByRefObject
{
    private AppDomain ad = null;
    private Worker w = null;

    public void Initialize(int count, int max)
    {
        // Handle the FirstChanceException event in all application domains except 
        // AD1. 
        if (count != 1)
        {
            AppDomain.CurrentDomain.FirstChanceException += FirstChanceHandler;
        }

        // Create another application domain, until the maximum is reached. 
        // Field w remains null in the last application domain, as a signal 
        // to TestException().  
        if (count < max)
        {
            int next = count + 1;
            ad = AppDomain.CreateDomain("AD" + next);
            w = (Worker) ad.CreateInstanceAndUnwrap(
                             typeof(Worker).Assembly.FullName, "Worker");
            w.Initialize(next, max);
        }
    }

    public void TestException(bool handled)
    {
        // As long as there is another application domain, call TestException() on 
        // its Worker object. When the last application domain is reached, throw a 
        // handled or unhandled exception. 
        if (w != null)
        {
            w.TestException(handled);
        }
        else if (handled)
        {
            try
            {
                throw new ArgumentException("Thrown in " + AppDomain.CurrentDomain.FriendlyName);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("ArgumentException caught in {0}: {1}", 
                    AppDomain.CurrentDomain.FriendlyName, ex.Message);
            }
        }
        else
        {
            throw new ArgumentException("Thrown in " + AppDomain.CurrentDomain.FriendlyName);
        }
    }

    static void FirstChanceHandler(object source, FirstChanceExceptionEventArgs e)
    {
        Console.WriteLine("FirstChanceException event raised in {0}: {1}",
            AppDomain.CurrentDomain.FriendlyName, e.Exception.Message);
    }
}

/* This example produces output similar to the following:

The last application domain throws an exception and catches it:

FirstChanceException event raised in AD3: Thrown in AD3
ArgumentException caught in AD3: Thrown in AD3

The last application domain throws an exception and does not catch it:

FirstChanceException event raised in AD3: Thrown in AD3
FirstChanceException event raised in AD2: Thrown in AD3
FirstChanceException event raised in AD0: Thrown in AD3
FirstChanceException event raised in Example.exe: Thrown in AD3
ArgumentException caught in Example.exe: Thrown in AD3
 */

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4

.NET Framework Client Profile

Supported in: 4

  • SecurityCriticalAttribute 

    Requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code.

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft