攔截無法預知的錯誤—Windows Form

 

我覺得夠robust的程式碼至少有1/3的CODE在是處理錯誤的行為,有時候也覺得很煩,一堆try,但在怎麼try,你還是有可能會miss,下面介紹的是.Net攔截全域的Exception的方法。

我現在習慣在 Main一開始先把這兩個函式掛上去
Application.ThreadException += new ThreadExceptionEventHandler(ThreadExceptionHandler);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

static void ThreadExceptionHandler(object sender, ThreadExceptionEventArgs e)
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
至於函式內實作的情況可以有很多,你可以給USER一個良好的錯誤回報,或是貼心的幫他把錯誤和StackTrace複製到剪貼簿,或者是透過網路寫到團隊的Bug Report系統,這樣總比他自己看到Runtime的錯誤視窗要好~

WPF好像換成 Application.Current.DispatcherUnhandledException,沒用過不知道~

留言

這個網誌中的熱門文章

好貴的東元冷氣維修--馬達啟動電容

台大醫院 婁培人 耳鼻喉科 就診

機車無法充電之整流器壞掉--$650