Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application won't die on unhandled exception?

Tags:

c#

.net

winforms

If my application ends up with an exception I can't handle I want it to show an error message to the user and quit. The problem is that the user is shown an exception dialog with the options Details, Continue, and Quit and if the user clicks Continue the application stays alive in "some" state which I don't want.

To replicate that with with the least amount of code I just created a Windows Forms application, added a button, and for the button click code just wrote:

throw new ApplicationException("I must crash now!!!");

When starting the compiled exe from the Debug folder, the Release folder, or starting the exe from the Release folder copied somewhere else (in case the pdb file is causing the problem) and clicking on the button I'm shown the Details / Continue / Quit dialog and if I say continue the application stays alive. How can I prevent the continue option from appearing?

I have this behaviour on my computer (Vista, Visual Studio 2008, Visual Studio 2010, creating the test application with VS2010) and also on a user computer (Windows 7).

like image 413
user755327 Avatar asked Feb 21 '23 11:02

user755327


2 Answers

It is Windows Forms that catches the exception and displays the dialog box you want to avoid. You can configure Windows Forms to not do this by using the Application.SetUnhandledExceptionMode method.

like image 71
Martin Liversage Avatar answered Feb 26 '23 22:02

Martin Liversage


You need to write an event handler for the AppDomain.UnhandledException event, where you show the user a nicer error message.

http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

Bear in mind, though, that the Exception could mean that the system is in an undefined state, so that even your error dialog could have trouble showing... You'll need to be able to gracefully crash.

At your application's starting point:

static void Main() {
    AppDomain currentDomain = AppDomain.CurrentDomain;
    currentDomain.UnhandledException += errorHandler;
    // Then start your app!
}

static void errorHandler(object sender, UnhandledExceptionEventArgs args) {
    // Show the user some error, but be prepared for disaster...
    // Examine the args.ExceptionObject (which is an Exception)
}
like image 30
Anders Marzi Tornblad Avatar answered Feb 26 '23 23:02

Anders Marzi Tornblad