techno
techno

Reputation: 6500

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?

Upvotes: 4

Views: 2386

Answers (3)

Kendall Frey
Kendall Frey

Reputation: 44316

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.

Upvotes: 2

Douglas
Douglas

Reputation: 54877

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.

Upvotes: 0

aybe
aybe

Reputation: 16652

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

Upvotes: 0

Related Questions