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?
Asked
Active
Viewed 250 times
2
-
Try this post: http://stackoverflow.com/questions/793100/globally-catch-exceptions-in-a-wpf-application – Tony Dec 16 '13 at 14:11
-
And application log too: http://blogs.msdn.com/b/calvin_hsia/archive/2013/07/31/10438571.aspx – Tony Dec 16 '13 at 14:12
-
@Tony thank you! Hmm... I was hoping for a simple answer. It is frustating to see there is no easy way. :-( – John Threepwood Dec 16 '13 at 14:17
-
You could add a uncaught exception handler. If you want me to post code let me know. – paparazzo Dec 16 '13 at 14:23
-
@Blam Sure, would be great to see. – John Threepwood Dec 16 '13 at 14:31
-
Added a code sample that has an appdomain handler, too. Hope it helps. – Allan Elder Dec 16 '13 at 14:44
2 Answers
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