我在代码中处理了所有未处理的异常,但每当出现异常(不是在调试期间),我都会看到错误窗口,一旦关闭该窗口,就会弹出“应用程序中发生未处理的异常”窗口。我该如何抑制它?
PS:我没有使用ASP.NET,而是使用Windows Forms
对于Windows Forms,您可以在调用Application.Run()
方法之前,在Main()
方法中添加以下内容,将未处理的异常(否则会导致未处理的异常窗口弹出)发送到异常处理程序:
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += myHandler;
你的表单处理方法应该长这样:
void myHandler(object sender, System.Threading.ThreadExceptionEventArgs e)
{
//do something
}
AppDomain.UnhandledException
。发生了非常严重的事情,你程序中的一个线程因心脏病而死亡。程序继续以有意义的方式运行的可能性为零,.NET通过终止程序来结束痛苦。AppDomain.CurrentDomain.UnhandledException
事件处理程序,并记录或显示e.ExceptionObject.ToString()
的值,以便知道导致事故的原因。这给了你一个提示如何修复你的代码。如果有的话,它可能是你自己无法修复的问题。例如某种类型的数据库服务器故障。有意隐藏错误是非常糟糕的想法。你的客户支持人员将不知道该怎么做。static void Main() {
try {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException +=
new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.Run(new Form1());
}
catch (Exception ex) {
MessageBox.Show("A fatal error has occurred. Please contact your admin\n" +
"Exception type: " + ex.GetType() + "\n" +
"Exception Message: " + ex.Message + "\n" +
ex.StackTrace, "Fatal Exception");
if (ex.InnerException != null) {
MessageBox.Show("Inner Exception:\n" +
"Exception type: " + ex.InnerException.GetType() + "\n" +
"Exception Message: " + ex.InnerException.Message + "\n" +
ex.StackTrace, "Fatal Exception (inner)");
}
}
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) {
throw new Exception(e.Exception.Message, e.Exception);
}