如何查看运行WPF应用程序时抛出的异常?

时间:2013-12-16 14:08:20

标签: c# wpf exception

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

2 个答案:

答案 0 :(得分: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
    }
}

}

答案 1 :(得分:0)

在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;
   }
}