当我们写代码的时候 对代码错误异常处理 有的时候会 没做处理
比如 我们执行如下代码 会引发程序崩溃
private void Button_Click(object sender, RoutedEventArgs e)
{
throw new Exception("字符串引发异常 日志输出");
}
这是我们不能接受的
当我们遇到这个问题 要一个一个的去寻找 担惊受怕 那有没有一个方法 能拦截所有的异常 不然程序挂掉那?
有的 WPF 中 dispatcherUnhandledException
我们在APP里 重写 Onstartup 方法
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
DispatcherUnhandledException += App_DispatcherUnhandledException;
}
void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show(e.Exception.ToString());
e.Handled = true;
// throw new NotImplementedException();
}
}
在这里 我们可以拦截所有的未处理异常 写日志 或者重启都可以