在wpf应用程序中捕获错误的最佳方法是什么。我已将以下内容添加到我的app.xaml.cs:
void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendFormat("{0}\n", e.Exception.Message);
stringBuilder.AppendFormat(
"Exception handled on main UI thread {0}.", e.Dispatcher.Thread.ManagedThreadId);
// attempt to save data
var result = MessageBox.Show(
"Application must exit:\n\n" + stringBuilder.ToString() + "\n\nSave before exit?",
"app",
MessageBoxButton.YesNo,
MessageBoxImage.Error);
if (result == MessageBoxResult.Yes)
{
MessageBox.Show(e.Exception.InnerException.ToString());
MessageBox.Show(e.Exception.InnerException.Message.ToString());
}
// Return exit code
this.Shutdown(-1);
// Prevent default unhandled exception processing
e.Handled = true;
}
private void Application_Startup(object sender, StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = e.ExceptionObject as Exception;
MessageBox.Show(ex.Message, "Uncaught Thread Exception", MessageBoxButton.OK, MessageBoxImage.Error);
}
但我仍然会在应用程序崩溃的情况下遇到错误并且错误未显示在消息框中。如何调试这些错误? Windows的事件日志没有向我显示任何有用的信息。当然,该应用程序在IDE中运行良好,所以这也没有真正帮助。
答案 0 :(得分:0)
在IDE中你可以捕获它。转到
调试 - >异常。强>
在对话框中,选中公共语言运行时异常的抛出复选框。
现在,您可以从IDE中捕获它。
HTH