2

When I start a WPF application and an exception is thrown by some method the program crashes. For debugging reasons it would be very interesting to see the exception stack. But where will it be printed?

John Threepwood
  • 15,593
  • 27
  • 93
  • 149

2 Answers2

1

You should hook up to the AppDomain.CurrentDomain.UnhandledException event and the Application.DispatcherUnhandledApplication event inside the App constructor or in the App.OnStartup .

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

}

Allan Elder
  • 4,052
  • 17
  • 19
0

In app.xaml.cs just add an uncaught exception handler
Be aware that exceptions from unmanaged code and elude this handler

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;
   }
}
paparazzo
  • 44,497
  • 23
  • 105
  • 176