简体   繁体   中英

Unable to capture Unhandled Exceptions in Winforms

I'm trying to capture all unhanded Exceptions in a C# Windows Forms Application. I have added the following code to the Program.cs file but the exceptions are not captured, I get Exceptions such as NullReferenceException . What am I doing wrong?

static void Main()
{ 
    System.Windows.Forms.Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
    System.Windows.Forms.Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(OnGuiUnhandedException);
    AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
    var form = new MainForm();
    form.ShowDialog();
}

private static void HandleUnhandledException(Object o)
{
    // TODO: Log it!
    Exception e = o as Exception;
    if (e != null)
    {
    }
}

private static void OnUnhandledException(Object sender, UnhandledExceptionEventArgs e)
{
    HandleUnhandledException(e.ExceptionObject);
}

private static void OnGuiUnhandedException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
    HandleUnhandledException(e.Exception);
}

EDIT:I'm able to catch the Exceptions when the program is run externally outside Visual Studio,But when debuging from visual studio i cant catch Exception.I know debugging is for error removal.Should i run the program in Build mode to capture Exceptions?

Try disabling exception catching in VS, as it seems to catch the exception before it gets to your handlers.

Debug > Exceptions... > Uncheck User-unhandled for Common Language Runtime Exceptions.

If you are on 64-bit Windows, you might want to check Debug->Exceptions and check that CLR exceptions are thrown.

Silent failures in C#, seemingly unhandled exceptions that does not crash the program

The events you're subscribing to only provide a means of inspecting the exception; they are not meant to allow you to suppress or recover from the exception.

From AppDomain.UnhandledException :

This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application.

If you want to recover from exceptions after logging them, you will need to use try–catch blocks around your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM