如何在WinForms应用程序中捕获所有未处理的异常?

编程入门 行业动态 更新时间:2024-10-23 13:29:48
本文介绍了如何在WinForms应用程序中捕获所有未处理的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 直到现在,我只是在 Program.cs 进入点的程序。这在调试模式下捕获所有异常,但是当我运行没有调试模式的程序时,异常不再被处理。我得到了未处理的异常框。

我不希望这样发生。我希望在非调试模式下运行时捕获所有异常。程序有多个线程,最好所有的异常都被同一个处理程序所捕获;我想在DB中记录例外。有没有人有任何建议如何做到这一点?

解决方案

看看 ThreadException文档:

public static void Main(string [] args) { //添加处理UI线程异常事件的事件处理程序。 Application.ThreadException + = new ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException); //设置未处理的异常模式,强制所有Windows窗体错误 //通过我们的处理程序。 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); //添加处理非UI线程异常事件的事件处理程序。 AppDomain.CurrentDomain.UnhandledException + = new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); }

调试时您可能还不想捕获异常,因为这样可以更容易调试这有点是一个黑客,但是你可以用

包装上面的代码if(!AppDomain.CurrentDomain.FriendlyName .EndsWith(vshost.exe)){...}

为了防止捕获异常调试。

Up until now, I just put a try/catch block around the Application.Run in the Program.cs entry point to the program. This catches all exceptions well enough in Debug mode, but when I run the program without the debug mode, exceptions don't get handled anymore. I get the unhandled exception box.

I don't want this to happen. I want all exceptions to be caught when running in non-debug mode. The program has multiple threads and preferably all exceptions from them get caught by the same handler; I want to log exceptions in the DB. Does anyone have any advice in how to do this?

解决方案

Take a look at the example from the ThreadException documentation:

public static void Main(string[] args) { // Add the event handler for handling UI thread exceptions to the event. Application.ThreadException += new ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException); // 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(CurrentDomain_UnhandledException); }

You might also want to not catch exceptions when debugging, as this makes it easier to debug. It is somewhat of a hack, but for that you can wrap the above code around with

if (!AppDomain.CurrentDomain.FriendlyName.EndsWith("vshost.exe")) { ... }

To prevent catching the exceptions when debugging.

更多推荐

如何在WinForms应用程序中捕获所有未处理的异常?

本文发布于:2023-11-17 11:58:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609930.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:应用程序   异常   未处理   如何在   WinForms

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!