Reputation: 16143
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?
Upvotes: 2
Views: 342
Reputation: 45096
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;
}
}
Upvotes: 0
Reputation: 4094
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
}
}
}
Upvotes: 1