我怎样才能使一些捕获的WinForms应用程序的所有“未处理”异常? [英] How can I make something that catches all 'unhandled' exceptions in a WinForms application?

查看:174
本文介绍了我怎样才能使一些捕获的WinForms应用程序的所有“未处理”异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到现在为止,我只是把周围的 Application.Run 的Program.cs 入口点计划。这捕获所有在调试模式不够好例外,但是当我没有调试模式下运行程序,例外情况没有得到了处理。我得到的未处理的异常对话框。

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.

我不希望这种情况发生。我想在非调试模式下运行时被抓住所有异常。该方案有多个线程和preferably从他们身上所有的异常,由相同的处理被逮住;我要记录在数据库例外。有没有人有在如何做到这一点有什么建议?

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?

推荐答案

在这个例子来看看从<一个href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx\">ThreadException文档:

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")) { ... }

要prevent调试时捕获异常。

To prevent catching the exceptions when debugging.

这篇关于我怎样才能使一些捕获的WinForms应用程序的所有“未处理”异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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