Click here to Skip to main content
15,884,177 members
Please Sign up or sign in to vote.
5.00/5 (1 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 ?

Thanks.
Posted

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 />}


 
Share this answer
 
Comments
Dalek Dave 23-Dec-10 20:13pm    
Good Answer.
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()):

C#
Application.SetUnhandledExceptionMode(
    UnhandledExceptionMode.CatchException);


ThreadException handler should be set up like this:

C#
Application.ThreadException += (sender, args) => {
    MessageBox.Show(string.Format(
            "{0}:\n\n{1}", args.Exception.GetType().Name, 
            args.Exception.Message),
        string.Format(
            " {0}: Error", ProductName),
        MessageBoxButtons.OK, MessageBoxIcon.Error);
}; //ThreadException
 
Share this answer
 
Comments
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.
--SA


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900