Click here to Skip to main content
14,578,463 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hello. This is my problem:
try<br />{<br />  Application.Run(new Form1());<br />}<br />catch(Exception ex)<br />{<br />  MessageBox.Show(ex.Message);<br />}

In Debug-Mode (F5), if exception is thrown, then it goes to catch block.
In Release-Mode (Ctlr-F5), if exception is thrown, then it shows "unexpected exception" from windows. Catch block is not called.

How can I catch unexpected exception in Release-Mode ?

Rate this:
Please Sign up or sign in to vote.

Solution 1

There's a special event that gets triggered whenever there's an unhandled exception. Your application could subscribe to the Application.ThreadException[^]-event.

Something like this (adapted from the MSDN-example, not tested);
{<br />// Add the event handler for handling UI thread exceptions to the event.<br />    Application.ThreadException += new ThreadExceptionEventHandler(MyErrorHandler);<br /><br />// Set the unhandled exception mode to force all Windows Forms errors <br />// to go through our handler.<br />    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);<br />    Application.Run(new Form1());<br />}<br /><br />private static void MyErrorHandler(object sender, ThreadExceptionEventArgs t)<br />{<br />    ShowMessage(t.ToString());<br />}

Dalek Dave 23-Dec-10 20:13pm
Good Answer.
Rate this:
Please Sign up or sign in to vote.

Solution 2

Eddy is right; and catching exception where Application.Run() is done makes no sense.

Also, to get Application.ThreadException triggered
don't forget this (in Main()):


ThreadException handler should be set up like this:

Application.ThreadException += (sender, args) => {
            "{0}:\n\n{1}", args.Exception.GetType().Name, 
            " {0}: Error", ProductName),
        MessageBoxButtons.OK, MessageBoxIcon.Error);
}; //ThreadException
Dalek Dave 23-Dec-10 20:14pm
Good Call.
Espen Harlinn 26-Feb-11 11:09am
Good reply - a 5
Sergey Alexandrovich Kryukov 26-Feb-11 19:19pm
Thank you.

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100