March 26, 2010

First Chance Exception Event .NET 4.0

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 .NET 4.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 MSDN Documentation 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 ALL exceptions within the application domain (With the exception of StackOverflow or access violations).

How Can This Help?

So the next logical question is, "great, buy 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 ALL exceptions 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 wasn'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 hault 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 .NET 4.0, C# 4.0, and Visual Studio 2010 content in the upcoming weeks!  Share any comments below.

tags: .NET 4.0
comments powered by Disqus

Content provided in this blog is provided "AS-IS" and the information should be used at your own discretion.  The thoughts and opinions expressed are the personal thoughts of Mitchel Sellers and do not reflect the opinions of his employer.

Content Copyright

Content in this blog is copyright protected.  Re-publishing on other websites is allowed as long as proper credit and backlink to the article is provided.  Any other re-publishing or distribution of this content is prohibited without written permission from Mitchel Sellers.