How does exception dispatching change with an unhandled exception handler?

回眸只為那壹抹淺笑 提交于 2019-12-11 10:29:21

问题


In short, MSDN describes exception dispatching for user mode application like this:

  1. the debugger gets notified of the first chance exception (if attached)
  2. an exception handler aka. try/catch is invoked (if available)
  3. the debugger gets notified of the second chance exception (if attached)
  4. the system cares about the unhandled exception (typically: terminate the process)

This sequence does not consider the presence of an unhandled exception handler. How does exception dispatching change when an unhandled exception handler is present?


回答1:


The unhandled exception handlers insert at position 3. The sequence is:

  1. the debugger gets notified of the first chance exception (if attached)
  2. an exception handler aka. try/catch is invoked (if available)
  3. the unhandled exception handlers (note the plural) are called (if available)
  4. the debugger gets notified of the second chance exception (if attached)
  5. the system cares about the unhandled exception (typically: terminate the process)

The following C# program demonstrates it. Depending on the .NET version, you'll a message of another unhandled exception handler, which is the .NET framework printing the exception and the call stack.

using System;
namespace UnhandledException
{
    static class Program
    {
        static void Main()
        {
            Console.WriteLine("Please attach the debugger now and press Enter.");
            Console.ReadLine();            
            AppDomain.CurrentDomain.UnhandledException += (sender, e) => Unhandled1();
            AppDomain.CurrentDomain.UnhandledException += (sender, e) => Unhandled2();
            try
            {
                Console.WriteLine("Throwing now.");
                // Will cause a first chance, because in try/catch
                throw new Exception("Any exception will do");
            }
            catch (Exception)
            {
                // Will cause first chance and second chance, because in NOT try/catch
                Console.WriteLine("In catch block.");
                throw;
            }
        }

        static void Unhandled1() => Console.WriteLine("In unhandled exception handler 1");
        static void Unhandled2() => Console.WriteLine("In unhandled exception handler 2");
    }
}

Commands required in the debugger (WinDbg):

.symfix
.reload
sxe clr
g; *** for the breakpoint due to attaching the debugger
g; *** first chance in try/catch
g; *** first chance outside try/catch
g; *** second chance


来源:https://stackoverflow.com/questions/34031107/how-does-exception-dispatching-change-with-an-unhandled-exception-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!