到目前为止,我只是在程序的 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/