gpt4 book ai didi

c# - 有没有人在 C# Windows 窗体应用程序中有一个经过验证的全局异常处理公式?

转载 作者:太空狗 更新时间:2023-10-30 01:09:18 25 4
gpt4 key购买 nike

全局意思是“在一个地方”,例如不是多次尝试...捕获例如在每个事件处理程序上。经证实的意思是“已知可以工作”- 我知道涵盖 .NET 和其他异常并不简单。

谢谢。

解决方案 根据以下答案编码。

注意:这被认为涵盖了来自其他线程的异常。

static class Program
{
static void MyHandler(Exception e)
{ MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

static void MyThreadExceptionEventHandler(object sender, ThreadExceptionEventArgs args)
{ MyHandler(args.Exception);
// App continues.
}

static void MyAppExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{ MyHandler((Exception)args.ExceptionObject);
// There follows a OS "needs to close" dialog, terminating app.
}

static void Main()
{

// For UI thread exceptions
Application.ThreadException +=
new ThreadExceptionEventHandler(MyThreadExceptionEventHandler);

// Force all Windows Forms errors to go through our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

// For non-UI thread exceptions
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(MyAppExceptionHandler);

Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}

最佳答案

在未处理异常时显示错误对话框并终止时的默认行为是一个很好的公式。如果您不喜欢此对话框的外观和感觉,您可以显示您的 own insteadprinciple 是相同的(很好的例子是 here ):

public static void Main(string[] args)
{
// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException
+= new ThreadExceptionEventHandler(/* YOUR OWN HANDLER */);

// Set the unhandled exception mode to force all
// Windows Forms errors to go through our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(/* YOUR OWN HANDLER */);

// Runs the application.
Application.Run(new /* YOUR MAIN FORM*/);
}

一般来说,异常处理没有神奇的“解决方案”——在调用任何方法之前,您必须了解 think 特定的异常。在这方面,Windows 窗体没有什么特别之处。

关于c# - 有没有人在 C# Windows 窗体应用程序中有一个经过验证的全局异常处理公式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7151204/

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