Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercepting all exceptions in C#, even when they're already caught [duplicate]

Visual Studio has the ability to break on all exceptions, even if they're caught. Note the checkbox under "Thrown" for CLR exceptions. When it's checked, the debugger breaks on every throw statement, even if there's a catch somewhere in the call stack.

Exception handling in Visual Studio

Is there a way of doing this in code as well? I'm using .NET 4.5.1 in a 64-bit class library. My objective is to log every exception and its stack trace. That way, when I'm testing my program on computers that don't have Visual Studio, I get a log of thrown exceptions, even those I handle by showing a dialog to the user. My program is multithreaded, so it would need to raise an event on a thrown exception in any thread as well.

One awful way of doing it is to just extend Exception, put some code in that new class's constructor, and make sure every exception extends it. But, that's not feasible given many of the exceptions that are thrown aren't even by my code but by the CLR itself.

So, ideas on how to raise or listen to an event that gets raised whenever an exception is thrown, even if that exception is caught? All I've seen are various ways of catching uncaught exceptions, which isn't what I want.

like image 546
user3466413 Avatar asked Dec 15 '22 20:12

user3466413


1 Answers

You can use AppDomain.FirstChanceException Event.

AppDomain.Current.FirstChanceException += (sender, eventArgs) =>
{
    Logger.Log(eventArgs.ToString());
}
like image 148
Eugene Podskal Avatar answered May 13 '23 00:05

Eugene Podskal