c# - 我怎样才能在 WinForms 应用程序中捕获所有 'unhandled' 异常?

标签 c# winforms debugging unhandled-exception

到目前为止,我只是在程序的 Program.cs 入口点中的 Application.Run 周围放置了一个 try/catch block 。这在 Debug模式下很好地捕获了所有异常,但是当我在没有 Debug模式的情况下运行程序时,异常不再得到处理。我得到未处理的异常框。

我不希望这样的事情发生。我希望在非 Debug模式下运行时捕获所有异常。该程序有多个线程,最好是它们的所有异常都被同一个处理程序捕获;我想在数据库中记录异常。有人对如何执行此操作有任何建议吗?

最佳答案

看看 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);
}

您可能还希望在调试时不捕获异常,因为这样更容易调试。这有点 hack,但为此你可以用

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

防止在调试时捕获异常。

编辑:一种检查您的应用程序是否在调试器中运行的替代方法,感觉比检查文件名更干净。

(参见 moltenform、Kiquenet 和 Doug 的评论)

if(!System.Diagnostics.Debugger.IsAttached) { ... }

这避免了使用不同于 vshost.exe 的调试器的问题。

关于c# - 我怎样才能在 WinForms 应用程序中捕获所有 'unhandled' 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5762526/

相关文章:

c# - MVC 中用于分页的映射路由

c# - 为什么 C# .NET WinForms 应用程序的控件在不同的机器上显示不同?黑盒测试方法

.net - 使用MS的Symbol Server-VS调试.NET代码不会显示变量的值

linux - 如何调查 "Server locked (outgoing flood)"错误?

c# - 使用 richtextbox 的运行作为 itemscontrol

c# - 更新 IDbCommand 参数的值

c# - 您如何自动调整 DataGridView 控件中的列大小并允许用户调整同一网格上的列大小?

C# - 透明窗体

visual-studio - 为什么在 Resharper/MSTest 下调试时引用的 dll 会被锁定?

C# 确保自定义强制转换在迭代父类(super class)型列表时使用父类(super class)型的子类型