如何在 WinForms 应用程序中创建一些可以捕获所有“未处理"异常的东西? [英] How can I make something that catches all 'unhandled' exceptions in a WinForms application?
问题描述
到目前为止,我只是在程序的 Program.cs
入口点中的 Application.Run
周围放置了一个 try/catch 块.这在调试模式下可以很好地捕获所有异常,但是当我在没有调试模式的情况下运行程序时,不再处理异常.我得到了未处理的异常框.
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?
推荐答案
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.
编辑:另一种检查在调试器中运行的应用程序的方法,比检查文件名更简洁.
EDIT: An alternate way to check for your application running inside a debugger that feels cleaner than checking a filename.
(见meltform、Kiquenet 和Doug 的评论)
(see comments by moltenform, Kiquenet and Doug)
if(!System.Diagnostics.Debugger.IsAttached) { ... }
这避免了使用与 vshost.exe
不同的调试器的问题.
This avoids the problem of using a different debugger than vshost.exe
.
这篇关于如何在 WinForms 应用程序中创建一些可以捕获所有“未处理"异常的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!