(This looks very similar to C# UnhandledException from another thread keeps looping, but am not trying to catch the exception here, just get the chance to log something)
I have some very simple C# code that sets up an UnhandledException event handler, then throws an exception:
class Program
{
static void Main(string[] args)
{
AppDomain currentDomain = AppDomain.CurrentDomain;
//currentDomain.UnhandledException += new UnhandledExceptionEventHandler(currentDomain_UnhandledException);
currentDomain.UnhandledException += (sender, eventArgs) =>
{
var exception = (Exception) eventArgs.ExceptionObject;
Console.WriteLine("Unhandled exception: " + exception.Message);
};
throw new AccessViolationException("Bleurgh");
}
}
It behaves as I expect from the console:
Unhandled exception: Bleurgh
Unhandled Exception: System.AccessViolationException: Bleurgh
at UnhandledExceptions.Program.Main(String[] args) in c:\code\sandbox\UnhandledExceptions\UnhandledExceptions\Program.cs:line 20
But when I attempt to debug it in Visual Studio it enters a loop, going into the event handler then dropping out to rethrow the Exception.
The same thing happens when I express the handler as a distinct static method.
Any ideas what's going on?
This is in Visual Studio 2010. EDIT: and .NET 4.
It seems to be down to the behaviour of the ExceptionAssistant specfically. When you continue, the assistant unwinds the call stack to the point at which the exception was thrown -- which causes the exception to be rethrown. I assume this is to allow you to make changes that would allow you to avoid the exception.
If under Tools\Options\Debugger\General you uncheck "Unwind the call stack on unhandled exceptions" then it'll just behave as an independent process would behave, and you'll see the process terminate.
This is how the debugger works, or shall we say, a "feature". If process is created by a debugger (F5) then debugger will prevent process termination, and point you to the line of code that would cause the process termination. Those "unhandled exceptions" are actually handled by the debugger, and so the execution never reaches to your code.
If debugger is attached to the process after the process was created (Ctrl+F5, and then attach) then debugger will eventually reach the unhandled exception "handler", but after exiting the handler it will still prevent process termination, and bring you back to the point where exception occurred.
来源:https://stackoverflow.com/questions/20517379/why-is-visual-studio-looping-when-debugging-unhandledexception-events