Back to all posts

First Chance Exception Event .NET 4.0

Posted on Mar 26, 2010

Posted in category:
Development
.NET

I have been spending quite a bit of time recently working with Visual Studio 2010 and .NET 4.0, working to keep up to date with the rapid additions to the .NET framework. In this blog posting, I'll share one fun new addition to the .NET framework that can be very helpful when creating applications and looking for a method to log all exceptions for logging purposes. Starting with .NET4.0 there is a new event available from the AppDomain object "FirstChanceException". The following explains a bit about this new feature and how it could be helpful.

What is the FirstChanceException Event

Although a descriptive name, it is important to understand the full meaning of this event. Per the MSDNDocumentation it "occurs when an exception first occurs in managed code, before the runtime has made its first pass searching for suitable exception handlers." So to help explain this in a bit more simple terms, the event is raised as soon as the event is thrown, even before any Try/Catch blocks are executed. So it will be raised on ALLexceptions within the application domain (With the exception of StackOverflow or access violations).

How Can This Help?

So the next logical question is, "great, but I care about this because why?" Well, consider a WPF or WinForms application that you are getting ready to distribute to clients, or for beta testing. By subscribing to the FirstChanceException event, you can quickly log out ALLexceptions that are occurring within your application, even those that are handled. This can allow you to identify locations in your code that might need to be re-worked, or alternatively it introduces plumbing for diagnostic processes that weren't possible before.

However, it is important to note that the FirstChanceException is a "notification" event, you CANNOT "handle" an exception within this event, so unhandled exceptions can still cause a halt to your application, however, you can be assured that the FirstChanceException event would be raised first, allowing you to log the critical information before your application crashes.

I hope this information has been helpful, I'll be working on more .NET4.0, C# 4.0, and Visual Studio 2010 content in the upcoming weeks! Share any comments below.