【发布时间】:2014-01-20 18:44:54
【问题描述】:
如果发生任何未处理的异常,我希望我的 exe 关闭。我已经尝试过How can I make something that catches all 'unhandled' exceptions in a WinForms application? 和Terminate application after unhandled exception 以及我在stackoverflow 中找到的其他几个帖子> 但没有效果我可以关闭程序而不显示消息框“您的应用程序中发生未处理的异常。如果单击继续,应用程序将忽略此错误并尝试继续如果单击退出,应用程序将立即关闭”。
我想退出应用程序,但我不希望显示此消息。非常感谢您的帮助。
代码:
[STAThread]
static void Main()
{
// Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
public static void MyHandler(object sender, UnhandledExceptionEventArgs e)
{
Exception exception = e.ExceptionObject as Exception;
System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();
Application.Exit();
proc.Kill();
}
出现异常时,它会显示此消息框。不能真正添加它,因为我没有声誉点。刚刚开户了。
我不想显示此消息框,也不想单击退出按钮退出程序。只想在遇到任何未处理的异常时退出。
【问题讨论】:
-
似乎是您的代码或第 3 方代码有问题。这通常不会发生。发布您的代码。更好的是查看运行应用程序时调试器中发生的情况。甚至可能添加日志记录并向我们展示 JIT 对话框中给出的异常
-
只需在主入口点包装一个 try/catch 并在 catch 逻辑中退出应用程序。此时的所有异常都应该冒泡到顶部。
-
这只是帮坏了的代码......你最好挖掘并找到异常并修复它。
-
我刚刚修改了win表单的代码。这就是您在 Win Forms 中处理其余(未处理的)异常的方式。看我的回答