Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress unhandled exception dialog?

Tags:

c#

exception

I'm handling all of my unhanded exception in the code but whenever one happens (not during debugging) I get my error window and as soon as it closes "Unhandled application exception has occurred in your application" window pops up. How do I suppress it?

PS : I am not using ASP.NET , I'm using Windows Forms

like image 319
Kristina Brooks Avatar asked Oct 22 '25 00:10

Kristina Brooks


2 Answers

You cannot suppress AppDomain.UnhandledException. Something really nasty happened, a thread in your program died from a heart attack. The odds that the program will continue to run in a meaningful way are zero, .NET puts an end to the misery by terminating the program.

Write an event handler for the AppDomain.CurrentDomain.UnhandledException event and log or display the value of e.ExceptionObject.ToString() so you know what caused the mishap. That gives you a hint how to fix your code. If any, it may well be something that you cannot fix yourself. Some kind of database server malfunction for example. Doing anything to intentionally hide the error is therefore a Very Bad Idea. Your customer's support staff will have no idea what to do.

like image 69
Hans Passant Avatar answered Oct 24 '25 15:10

Hans Passant


For Windows Forms, you can send unhandled exceptions (that would otherwise cause the unhandled exception window to pop up) to your exception handler by adding the following in the Main() method, before the Application.Run() method is called:

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

You can subscribe your handler to the unhandled exception event by adding the following to the form's constructor or elsewhere:

Application.ThreadException += myHandler;

And your form's handler method would look like this:

void myHandler(object sender, System.Threading.ThreadExceptionEventArgs e)
{
     //do something
}

You can find more information about this on the msdn.

like image 39
erli Avatar answered Oct 24 '25 14:10

erli