【问题标题】:WPF - catch exception in MainWPF - 在 Main 中捕获异常
【发布时间】:2023-03-14 21:51:01
【问题描述】:

在项目WPF中;我发现如果在Main 中引发异常,它不会被捕获,因为new Appexception 引发之后执行。如果exception 出现在new App 之后,则可以被捕获。

我想知道我必须在Main 中重新捕获它,或者有另一种方法来捕获它可用的方法。

App.xaml

public partial class App : Application
{
    public App()
    {
        SetupExceptionHandling();
    }

    private void SetupExceptionHandling()
    {
        AppDomain.CurrentDomain.UnhandledException += (s, e) =>
        {
            //log
        };

        this.DispatcherUnhandledException += (s, e) =>
        {
            //log
        };

        TaskScheduler.UnobservedTaskException += (s, e) =>
        {
            //log
        };
    }

    [STAThread]
    public static void Main()
    {
        try
        {
            throw new Exception();
            var app = new App();
        }catch(Exception ex)
        {
            //log
        }
    }
}

【问题讨论】:

  • 在 Main 而不是 App 中调用 SetupExceptionHandling 是否有效?
  • 试过了,但 DispatcherUnhandledException 适用于 App
  • @kennyzx 我更新了问题
  • 在 Main 方法中为 AppDomain.CurrentDomain.UnhandledException 设置处理程序就足够了,因为它是针对 any 线程中的 any 未处理异常引发的。您可以将其他两个保留在 App 类中。
  • 还有另一种方法可以将 3 个手柄放在同一个方法中吗?

标签: c# wpf exception-handling


【解决方案1】:

创建2个方法:

一个用于Main,另一个用于App

看起来很丑,但我想不出更好的方法。

public partial class App : Application
{
    public App()
    {
        SetupExceptionHandlingInApp();
    }

    private static void SetupExceptionHandlingInMain()
    {
        AppDomain.CurrentDomain.UnhandledException += (s, e) =>
        {
            //log
        };

        TaskScheduler.UnobservedTaskException += (s, e) =>
        {
            //log
        };
    }

    private void SetupExceptionHandlingInApp()
    {            
        this.DispatcherUnhandledException += (s, e) =>
        {
            //log
        };                      

    }

    [STAThread]
    public static void Main()
    {
        SetupExceptionHandlingInMain();
        var app = new App();
        throw new Exception();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 2014-07-15
    • 2018-11-01
    • 1970-01-01
    相关资源
    最近更新 更多