2013-08-04 39 views
1

我正在使用Visual Studio 2012,C#,.NET 4.5創建Windows Forms應用程序; Windows 7.異常處理程序僅在從Visual Studio中運行時才起作用

我想用我自己的錯誤處理程序處理任何未處理的異常。我寫了一些如下所示的代碼。我甚至嘗試了兩種不同的錯誤處理方式。

現在,當我在Visual Studio(2012)中運行此程序時,此工作非常好!

但是,當我從資源管理器啓動程序,然後我的錯誤處理程序永遠不會被調用;相反,總是會彈出.NET Framework的標準錯誤處理程序。

那麼我做錯了什麼?

static void Main() 
{ 
    try 
    { 
     AppDomain currentDomain = AppDomain.CurrentDomain; 
     currentDomain.UnhandledException += new UnhandledExceptionEventHandler(HandleUnhandledException); 
     Application.Run(new frmMainFrame()); 
    } 
    catch (Exception ex) 
    { 
     // Here is my error handler .... 
    } 
} 

static void HandleUnhandledException(object sender, UnhandledExceptionEventArgs args) 
{ 
    Exception ex = (Exception) args.ExceptionObject; 
    // Here is my error handler .... 
} 

回答

1

掛鉤Application.ThreadException以及。

或設置Application.SetUnhandledExceptionModeUnhandledExceptionMode.ThrowException讓您的appdomain處理程序啓動。

+0

是的,工作! Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException); 似乎Visual Studio默認情況下會設置此模式,而Explorer不會。謝謝 !! –

+0

@Giosco:資源管理器與它無關。 – siride

+0

@siride - 你能解釋一下嗎?據我現在瞭解,起始環境設置了UnhandledExceptionMode,而Visual Studio和Explorer似乎做了不同的處理。 –

0

首先,我會使用Debugger.Break()方法將您的程序附加到有問題的代碼部分。也許只是檢查currentDomain是否不爲空。假設您不提出強制CLI停止的異常。

相關問題