我可以在C#中创建一个全局异常处理程序,以使代码随后继续运行吗? [英] Can I create a global exception handler in C# that lets the code continue running afterward?

查看:352
本文介绍了我可以在C#中创建一个全局异常处理程序,以使代码随后继续运行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET中,默认的异常处理程序将使用户继续运行程序。但是,我希望有一个全局异常处理程序,它将堆栈跟踪保存到 errorlog.txt文件中,以便用户可以将其发送给我,而不必记住单击详细信息并将其复制出对话框(并删除所有关于已加载程序集等的无用废话)。但是,当我这样做时,代码不知道如何继续,所以我所能做的就是退出应用程序。有什么办法可以让两全其美吗? (是的,我知道我要的实际上是带有日志记录的 On Error Resume Next,但我真的认为这将是有用的!)

In .NET, the default exception handler will let the user continue running the program. However, I'd like to have a global exception handler that saves the stack trace to an "errorlog.txt" file so the user can send it to me and doesn't have to remember to click "Details" and copy it out of the dialog (and remove all the useless crap about loaded assemblies and such). But when I do this, the code doesn't know how to continue, so all I can do is exit the app. Is there any way to have the best of both worlds? (Yes, I know what I'm asking for is essentially "On Error Resume Next" with logging, but I really think it would be useful!)

推荐答案

您可以编写在每个 catch 块中调用的全局异常处理程序方法,该方法会将堆栈跟踪写入您要保存的任何位置。但是您需要编写 try。 。 。为每个需要它们的操作捕获块,并在每个操作中调用异常处理程序。

You can write a global exception handler method that you call in every catch block, which writes the stack trace where ever you want to save it. But you'd need to write try . . . catch blocks for every operation that needs them and call the exception handler in each.

您还可以在 MyApplication.UnhandledException 处理程序,用于所有未处理的事件。但是,在那种情况下,当控制权转到该方法时,该程序将不会继续运行。

You can also call that global exception handler method in the MyApplication.UnhandledException handler for all unhandled events. But when control gets to that method in that case, the program is not going to continue running.

这篇关于我可以在C#中创建一个全局异常处理程序,以使代码随后继续运行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆