今天在學習 Windows Phone 7WP7() 編程時,接觸到 WP7 的異常處理。
主要是異常的人性化顯示。
在?App.xaml.cs 的?RootFrame_NavigationFailed (自動生成的) 函數(shù)中對?e.Handled 進行賦值。
先看未修改的代碼:
//?Code?to?execute?if?a?navigation?fails
private?void?RootFrame_NavigationFailed(object?sender,?NavigationFailedEventArgs?e)
?{
????????????if?(System.Diagnostics.Debugger.IsAttached)
????????????{
????????????????//?A?navigation?has?failed;?break?into?the?debugger
????????????????System.Diagnostics.Debugger.Break();
????????????}
}
修改后的代碼:
private?void?RootFrame_NavigationFailed(object?sender,?NavigationFailedEventArgs?e)
{
????if?(System.Diagnostics.Debugger.IsAttached)
????{
????????//?A?navigation?has?failed;?break?into?the?debugger
????????System.Diagnostics.Debugger.Break();
????}
?????
????e.Handled?=?true;
????Page1.ExceptionInfo?=?e.Exception;
????(RootVisual?as?Microsoft.Phone.Controls.PhoneApplicationFrame).Source?=?new?Uri("/Page1.xaml",?UriKind.Relative);
}將異常信息直接顯示在 Page 1 頁面的 Text 控件中。當然,如果為了讓“用戶”看懂異常信息,直接這樣顯示是不行的。需要將這種“計算機”語言轉為自然語言。
其中,關鍵的一句是:
e.Handled?=?true; 如果沒有此句,系統(tǒng)會將異常最終傳遞到:Application_UnhandledException()?函數(shù)中進行處理,并導致應用程序直接關閉。





