use*_*073 4 error-handling exception-handling c#-3.0 c#-4.0
我试图在我的程序中捕获任何unhandeled Exception,我在Program主类中使用此代码
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.Run(new Form1());
}
public static void CurrentDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show((e.ExceptionObject as Exception).Message, "Unhandled domain Exception");
Application.Exit();
}
Run Code Online (Sandbox Code Playgroud)
现在我的表单form1,我尝试创建一个简单的异常:除以零,没有try catch块,主模块中的代码确实拦截了异常,但我仍然有MS Visual studio对话框.应用程序不会退出.当然在实际情况下,我会记录/邮寄错误.但我想理解为什么在我拦截我的异常后继续执行?谢谢
从主UI线程中捕获所有异常对我有用:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Add handler for UI thread exceptions
Application.ThreadException += new ThreadExceptionEventHandler(UIThreadException);
// Force all WinForms errors to go through handler
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// This handler is for catching non-UI thread exceptions
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.Run(new Form1());
}
private static void CurrentDomain_UnhandledException(Object sender, UnhandledExceptionEventArgs e)
{
try
{
Exception ex = (Exception)e.ExceptionObject;
MessageBox.Show("Unhadled domain exception:\n\n" + ex.Message);
}
catch (Exception exc)
{
try
{
MessageBox.Show("Fatal exception happend inside UnhadledExceptionHandler: \n\n"
+ exc.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}
// It should terminate our main thread so Application.Exit() is unnecessary here
}
private static void UIThreadException(object sender, ThreadExceptionEventArgs t)
{
try
{
MessageBox.Show("Unhandled exception catched.\n Application is going to close now.");
}
catch
{
try
{
MessageBox.Show("Fatal exception happend inside UIThreadException handler",
"Fatal Windows Forms Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}
// Here we can decide if we want to end our application or do something else
Application.Exit();
}
}
Run Code Online (Sandbox Code Playgroud)