【发布时间】:2018-11-01 15:17:19
【问题描述】:
我正在尝试在我的 WPF 应用程序中捕获所有异常。我尝试了以下代码,但它不起作用我不知道为什么?
<Application x:Class="DBFilter.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml"
Exit="Application_Exit"
DispatcherUnhandledException ="AppDispatcherUnhandledException"
>
<Application.Resources>
</Application.Resources>
</Application>
App.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(AppDomainUnhandledExceptionHandler);
System.Windows.Forms.Application.ThreadException += new
ThreadExceptionEventHandler(Application_ThreadException);
Application.Current.DispatcherUnhandledException += new
DispatcherUnhandledExceptionEventHandler(AppDispatcherUnhandledException);
}
void AppDomainUnhandledExceptionHandler(object sender,
UnhandledExceptionEventArgs ex)
{
Exception ex = (Exception)ea.ExceptionObject;
MessageBox.Show(ex.Exception.InnerException.Message);
}
void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
MessageBox.Show(e.Exception.InnerException.Message);
}
void AppDispatcherUnhandledException(object
sender,DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show(e.Exception.InnerException.Message);
}
稍后,我会将所有异常写入日志表。
【问题讨论】:
-
不是每个异常都有内部异常。
-
什么不起作用?当你运行你的程序时会发生什么?你预计会发生什么?