如何正确捕获WinForms应用程序中所有未处理的异常

本文关键字:未处理 异常 应用程序 何正确 WinForms | 更新日期: 2023-09-27 18:11:05

我想为WinForms应用程序中任何线程的所有未处理异常设置处理程序方法。我没有自己创建任何应用程序域。

根据UnhandledException文档,我需要通过Application.SetUnhandledExceptionMode方法设置UnhandledExceptionMode.ThrowException模式来捕获主线程的异常:

在使用Windows窗体的应用程序中主应用程序线程导致应用程序。线程异常事件提高。如果处理此事件,则默认行为是未处理异常不会终止应用程序,尽管应用程序处于未知状态。在这种情况下,未引发UnhandledException事件。这种行为是可以改变的通过使用应用程序配置文件,或使用应用程序。SetUnhandledExceptionMode方法将模式更改为UnhandledExceptionMode。在ThreadException事件之前抛出异常汉德勒已经上钩了。这只适用于主应用程序线程。UnhandledException事件会因未处理而引发其他线程抛出的异常

因此,结果代码看起来像下面这样:
    public static void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e)
    {
        // ...
    }
    [STAThread]
    static void Main(string[] args)
    {
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionEventHandler);
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm(pathToCheck));
    }

可以吗?它会捕获所有未处理的异常从任何线程(包括主线程,UI线程和Task类创建的所有线程)?我对文档的理解正确吗?

是的,我在这里看到了这样的问题,但是我不明白为什么我还要使用下面的代码:

Application.ThreadException += new     
  ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);

如何正确捕获WinForms应用程序中所有未处理的异常

您应该订阅这两个事件。注意,即使这样也不会自动捕获来自其他线程的所有内容。例如,当异步调用委托时,只有在调用EndInvoke时才会将异常传播到调用线程。

    [STAThread]
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException +=
            (sender, args) => HandleUnhandledException(args.ExceptionObject as Exception);
        Application.ThreadException +=
            (sender, args) => HandleUnhandledException(args.Exception);
    }
    static void HandleUnhandledException(Exception e)
    {
        // show report sender and close the app or whatever
    }