FIRST CHANCE Exceptions

Few months ago I was preparing to 70-486 MVC exam and I found a great way of exception handling in Exam ref Book. I decided to make a quick note based on this material.

Introduction
First chance exception is debugging concept to handle exceptions before they have been handled by an error handler.
Sometimes you want to catch “first-chance” exceptions because it’s important to see what’s happening when it’s being thrown, even before someone is catching it. It’s a good place to put some generic error statistic module, where developers can track exceptions in a system and repair some bugs.

Enable
To configure Visual Studio to detect first chance exceptions, ensure that the Thrown box is checked for the Common Language Runtime Exception row in the DEBUG Exceptions dialog box, as shown

first chance exception

Skip
As of .NET 2.0, if you mark an method with the DebuggerNonUserCode attribute, the debugger will ignore first chance exceptions.

Capture globally

To make this mechanism began to work let’s modify Application_Start method in Global.asax.cs. First, create FirstChanceException event handler. Later on, let’s put some logic into the handler. We can specify the types of exceptions and implement the appropriate modules to process.

 
 protected void Application_Start()
 {
   AppDomain.CurrentDomain.FirstChanceException +=
   FirstChanceException;

   AreaRegistration.RegisterAllAreas();

   WebApiConfig.Register(GlobalConfiguration.Configuration);
   FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
   RouteConfig.RegisterRoutes(RouteTable.Routes);
   BundleConfig.RegisterBundles(BundleTable.Bundles);
   AuthConfig.RegisterAuth();
 }

 protected void FirstChanceException(object sender,
          System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
 {
     if (e.Exception is NotImplementedException)
     {
         // do something special when the functionality is not implemented
     }
 }

This mechanism may be very helpful in application monitoring. You can track many errors and fix them – which will improve performance and stability. Certainly gained knowledge will be useful to me in the next projects that’ll conquer the world !;]

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *