如何在WinForms应用程序中捕获所有未处理的异常? [英] How can I make something that catches all 'unhandled' exceptions in a WinForms application?
问题描述
Program.cs
Application.Run 周围放置一个try / catch块>进入点的程序。这在调试模式下捕获所有异常,但是当我运行没有调试模式的程序时,异常不再被处理。我得到了未处理的异常框。 我不希望这样发生。我希望在非调试模式下运行时捕获所有异常。程序有多个线程,最好所有的异常都被同一个处理程序所捕获;我想在DB中记录例外。有没有人有任何建议如何做到这一点?
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应用程序中捕获所有未处理的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!