次の方法で共有


First Chance Exception vs Second Chance Exception

There are many situations where customers ask me: what exception should I care about, first or second chance?

I believe that that it is particularly important to understand the difference between them in order to properly answer to the question.

Let’s consider the following code:  

         static void Main(string[] args)
        {
            try
            {
                Random r = new Random();
                int a = r.Next(2);
                double b = r.Next(10) / a;
                Console.WriteLine("Output is "+b);
            }
            catch (DivideByZeroException)
            {
                Console.WriteLine("It is not possibile to divide by zero!");
            }
            Console.WriteLine("Press a key to exit");
            Console.ReadKey();
        }

As you can see, the yellow section of code could raise an exception in case that variable a is equal to zero.

So what is a first chance exception?

We talk about a first chance exception as soon as the object DivideByZeroException is defined in memory by .Net framework runtime.

The runtime defines it in order to properly report the "exceptional situation" to our application.

In case that you add a debugger to our application, the debugger has the possibility to take a memory dump of our process at that moment in time.  

According to above code, the exception is properly handled so code execution continue without issues. It allows us to understand that a first chance exception does not necessarily mean we have a problem in our code.

When do we talk about second chance exception? In case our code has not any catch block to manage the exceptional situation (divide by zero in our case), we have an application crash. In case a debugger is attached to our application, it is notified about this event and we have the possibility to collect a memory dump exactly before our process crashes.

A second chance exception means that your process did not handle an exception and your software is going to crash.

The consideration you could have in mind is this one: to troubleshooting a crash, I should take care only of second chance exception!  Please do not come to conclusion to fast Smile. Well, it is correct that in case of crash troubleshooting starts from a memory dump collected during a second chance exception, anyway in complex scenario with multithread application, it could be required to have a dump that shows all threads'activities during the exception definition: so during the first chance exception.

Hope this help.

Carmelo