2011-06-09 85 views
24

有沒有辦法在代碼中的任何位置捕獲展開的代碼?我想要捕獲異常並以類似的方式處理它們,而不是爲每個功能編寫try catch塊。在Windows窗體應用程序中捕獲應用程序異常

+1

這不是你想要做的事情,而不是在本地處理,而是另外處理。看到可能的答案。 – Jodrell 2011-06-09 11:41:45

回答

35

在Windows窗體應用程序,當異常在應用程序中的任何位置拋出(在主線程或在異步調用),可以通過在該ThreadException事件註冊抓住它應用。通過這種方式,您可以用相同的方式處理所有異常。

Application.ThreadException += new ThreadExceptionEventHandler(MyCommonExceptionHandlingMethod) 

private static void MyCommonExceptionHandlingMethod(object sender, ThreadExceptionEventArgs t) 
{ 
    //Exception handling... 
} 
+3

以防萬一它可能幫助某人。請確保在運行應用程序(Application.Run(...);)之前註冊到事件處理程序(Application.ThreadException + = ...)。否則,它將不起作用(正如它發生在我身上) – 2014-11-10 23:24:24

+0

這回答了這個問題,但Brian Dishaw在他的回答中的鏈接非常全面,並且涵蓋了所有(如果不是大多數)用例。在生產應用程序中唯一沒用的方法是返回帶有錯誤消息的對話框的方法。一個真正的生產應用程序將發送到事件日誌,而不是在應用程序中彈出一個對話框。 – MacGyver 2016-02-01 16:08:10

15

顯而易見的答案是將異常處理程序放在執行鏈的頂部。

[STAThread] 
static void Main() 
{ 
    Application.EnableVisualStyles(); 
    Application.SetCompatibleTextRenderingDefault(false); 
    try 
    { 
     Application.Run(new YourTopLevelForm()); 
    } 
    catch 
    { 
     //Some last resort handler unware of the context of the actual exception 
    } 
} 

這將捕獲您的主GUI線程上發生的任何異常。如果您還想全局捕獲所有線程上發生的異常,您可以訂閱AppDomain.UnhandledException事件並在那裏處理。

Application.ThreadException += 
    new ThreadExceptionEventHandler(MyCommonExceptionHandlingMethod) 
private static void MyCommonExceptionHandlingMethod(
               object sender, 
               ThreadExceptionEventArgs t) 
{ 
    //Exception handling... 
} 

代碼從Charith J's answer

現在到諮詢複製...

這些選項只能作爲最後的手段,比方說,如果要抑制意外捕獲的異常從演示文稿到用戶。只要有可能,當你知道有關異常情況的事情時,你應該儘快趕上。更好的是,你可以對這個問題做些什麼。

結構化的異常處理可能看起來像一個不必要的開銷,你可以解決所有的問題,但它存在,因爲情況並非如此。更重要的是,這項工作應該在編寫代碼時完成,當開發人員擁有更新的邏輯時。不要懶惰,稍後離開這項工作,或讓更多的專業開發人員拿起。

道歉,如果你已經知道並做到這一點。

+3

@Downvoter,感謝任何批評者,我在這裏學習。 – Jodrell 2011-06-09 11:56:14

+0

這聽起來對我很好。我看不到任何投下的理由... – CharithJ 2011-06-09 23:19:36

4

參見AppDomain.UnhandledExceptionApplication.ThreadException

21

我認爲這是一個接近,因爲你可以得到你在尋找勝利形式的應用程序。

http://msdn.microsoft.com/en-us/library/ms157905.aspx

// Add the event handler for handling UI thread exceptions to the event. 
Application.ThreadException += new ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException); 

// Set the unhandled exception mode to force all Windows Forms errors to go through 
// our handler. 
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); 

// Add the event handler for handling non-UI thread exceptions to the event. 
AppDomain.CurrentDomain.UnhandledException += 
    new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); 

沒有做所有的運行有一些例外的風險,這些措施得到未處理。

+0

這是我的主循環(我的應用程序開始隱藏,帶有狀態欄圖標)。在您的代碼中,我仍然需要在try/catch中包裝新的Form1(); Application.Run();'... – doekman 2017-02-27 13:29:48

相關問題