I would like to have some kind of catch-all exceptions mechanism in the root of my code, so when an app terminates unexpectedly I can still provide some useful logging.
Something along the lines of
static void Main () {
if (Debugger.IsAttached)
RunApp();
else {
try {
RunApp();
}
catch (Exception e) {
LogException(e);
throw;
}
}
}
While this all works fine, my problem is when I want to attach the debugger after the exception has been raised.
Since the exception escapes to the runtime, windows will prompt to attach visual studio, except, since it has been rethrown, all locals and parameters further up the stack have been lost.
Is there anyway to log these exceptions, while still providing a way to attach the debugger and retain all useful information?
As Paul Betts already mentioned, you might be better off using the AppDomain.UnhandledException event instead of a try/catch block.
In your UnhandledException event handler you can log/display the exception and then offer the option to debug e.g. show a form with the exception details and buttons to ignore, debug or quit.
If the user selects the debug option, call System.Diagnostics.Debugger.Break() which allows the user to attach whatever debugger they want with the full call stack still available.
Obviously, you could disable this option for any builds you know you're not ever going to be attaching the debugger to.
class Program
{
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += ExceptionHandler;
RunApp();
}
static void ExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
Console.WriteLine(e.ExceptionObject);
Console.WriteLine("Do you want to Debug?");
if (Console.ReadLine().StartsWith("y"))
Debugger.Break();
}
static void RunApp()
{
throw new Exception();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With