gpt4 book ai didi

c# - 全局异常捕获仅在调试 WinForms 应用程序时有效

转载 作者:太空宇宙 更新时间:2023-11-03 13:33:42 26 4
gpt4 key购买 nike

我在我的 WinForms 应用程序中实现了以下全局异常 catch:

static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyMainForm());
}
catch (Exception ex)
{
MessageBox.Show("UNHANDLED EXCEPTION: The program will be terminated. Details follow:\n\n" +
getExceptionInfoWithDebuggerOutput(ex),
"Global Exception",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}

然后在代码下面,引发了一个异常(像这个——完全是我的健忘造成的):

public partial class MyPage : UserControl
{

void func1()
{
SqlConnectionStringBuilder conStr = null;

//... later
conStr.DataSource = strServer; //<<--- Where exception is raised
}
}

现在,如果我正在调试我的项目,我会看到来自全局异常处理程序的 Global Exception 消息框。

但是如果我没有调试我的项目并以 Ctrl+F5 运行它,或者如果我构建一个 Release 项目,我会得到以下窗口而不是我上面编码的窗口:

enter image description here

知道如何让我的全局异常处理程序代替处理吗?

最佳答案

您应该 Hook 一个事件,例如 AppDomain.UnhandledException .

这些事件在您在 Release模式下看到的全局错误处理程序之前引发。这允许您在退出之前记录错误……以更好的方式。

还会引发其他事件。例如,Application.ThreadException .阅读文档将使您更好地了解自己的特定需求。

我必须指出,您看到的错误是 NullReferenceException.. 最好在您的代码中很好地处理它。不过, Hook 这些事件并记录异常是一个好主意。

关于c# - 全局异常捕获仅在调试 WinForms 应用程序时有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19484774/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com