Exception handling in windows application c# [duplicate]
In a C# windows application I have written code to display all exceptions. I tried the code below. When running in trace mode (pressing F5) it worked (I have written my UI event functions which has created the exceptions). But when I run the standalone exe it does not catch the exception. Instead it is displayed as an unhandled exception.
static void Main()
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
MessageBox.Show(ex.StackTrace);
}
}
Does anybody know about it?
You better use the unhandled exception handler:
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CatchUnhandledException);
More information on the MSDN:
- http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx
- http://msdn.microsoft.com/en-us/library/ms157905.aspx#Y600
- https://blogs.msdn.com/b/tom_krueger/archive/2005/02/17/375602.aspx
Try to add an UnhandledException
handler:
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler((o, e) => {
Exception theException = (Exception)e.ExceptionObject;
/* CODE TO SHOW/HANDLE THE EXCEPTION */
Debug.WriteLine(theException.Message);
});
I usually go with this approach:
static void Main()
{
Application.ThreadException += ExceptionHandler;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
static void ExceptionHandler(object sender, ThreadExceptionEventArgs e)
{
const string errorFormat = @"some general message that a error occured";
//error logging, usually log4.net
string errMessage = string.Format(errorFormat, e.Exception.Message, e.Exception.StackTrace)
DialogResult result = MessageBox.Show(errMessage, "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Error);
if (result == DialogResult.No)
{
Application.Exit();
}
}
This displays the exception's message and stack trace to the user, and asks to terminate the application. This is quite usefull in test scenarios or in-house application, but it's generally a bad idea to release detailed stack traces of messages in the wild.
精彩评论