AppDomain.FirstChanceException Event

One interesting feature that was introduced since .NET 4.0 was AppDomain.FirstChanceException



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

This means that whenever an exception occurs in your managed code, all subscribers of above mentioned event will be notified with exception details.

It is called first chance because this event is notified to the debugger or subscribers even before the actual program gets it. Event before Try/Catch block (if any) are executed. It serves as "first chance" to take a note of the exception thrown.

All exceptions except Stackoverflow and access violation exceptions will be notified to this event.

This is subscribed by your Visual Studo debugger, you can verify that by running an sample and throw an exception from your program. You will see following or similar output in your visual studio output window (Debug):

A first chance exception of type 'System.InvalidOperationException' occurred in FirstChanceExceptionDemo.exe

Note: This is only available as a notification, you cannot handle or change anything in your application workflow from this event (using eventArgs).

This notification will fire once if the exception is handled in your code as "first chance", if the application is not handling this exception then FirstChanceException event may get raised recursively and may result in stack overflow in your application.

This can be used to log exceptions occurring in your application and most importantly can be used in your developement or debugging sessions to get hold of any exceptions during the execution of your application.

I have always used this event to get hold of exceptions occurring in code I work on and also to find out other fellow programmers Try/Catch blocks (that might be swallowing exception or not implemented correctly).

Hope it helps your.
Happy Coding !!