【问题标题】:How to look up which exception was thrown when running a WPF application?如何查找运行 WPF 应用程序时引发的异常?
【发布时间】:2014-01-03 23:01:46
【问题描述】:

当我启动 WPF 应用程序并且某些方法引发异常时,程序崩溃。出于调试原因,查看异常堆栈会非常有趣。但是会在哪里打印呢?

【问题讨论】:

标签: c# wpf exception


【解决方案1】:

您应该在 App 构造函数或 App.OnStartup 中连接AppDomain.CurrentDomain.UnhandledException 事件和Application.DispatcherUnhandledApplication 事件。

public partial class App : Application
{

    //Either here
    public App()
    {
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        Dispatcher.UnhandledException += Dispatcher_UnhandledException;
    }

    //Or here
    protected override void OnStartup(StartupEventArgs e)
    {
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        Dispatcher.UnhandledException += Dispatcher_UnhandledException;
    }

    void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
        //add logging
    }

    void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        //add logging
    }
}

}

【讨论】:

    【解决方案2】:

    在 app.xaml.cs 中只需添加一个未捕获的异常处理程序
    请注意非托管代码的异常并避开此处理程序

    this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
    
    if (!string.IsNullOrEmpty(e.Exception.StackTrace))
    {
       sb.AppendLine("e.Exception.StackTrace ");
       int count = 0;
       foreach (string line in e.Exception.StackTrace.Split('\n'))
       {
           sb.AppendLine(line.Trim());
           count++;
           if (count > 10) break;
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 1970-01-01
      • 2018-09-23
      • 2018-06-13
      相关资源
      最近更新 更多