FIRST CHANCE Exceptions

Few months ago I was preparing to 70-486 MVC exam and i found great issue of exception handling in Exam ref Book and decided to create this note.

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 if someone is catching it. It’s good place to put some error statistic module, where developers can track exceptions in 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 skip first chance exceptions in it.

Capture globally

To make this mechanism began to work let’s modify Application_Start method in Global.asax.cs:
Create FirstChanceException event handler
Define some logic in handler. We can specify the types of exceptions and implement the appropriate types of processing it
Hook it to current domain

 
 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
     }
 }

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 *