2010-09-13 45 views
3

有沒有一種方法可以在不使用try catch方法的情況下集中處理錯誤或異常處理?C#中是否存在集中式錯誤處理過程?

+1

你使用WinForms嗎? – Branimir 2010-09-13 11:06:42

+0

您是否對集中式錯誤回退感興趣,以便在關閉應用程序之前記錄並顯示友好的消息,或者您是否正在討論實際處理錯誤的中心位置。前一種情況由'Application.ThreadException'(在WinForms中)和'AppDomain.UnhandledException'支持。後一種情況通常是不可能的,因爲在中央位置通常沒有足夠的上下文來做出關於如何從錯誤中恢復的決定。 – 2010-09-13 13:25:24

回答

2

如果這是ASP.NET,你可以添加一個Global.asax文件到網站,並處理Application_Error方法。

這是怎麼了,我一般使用它:

void Application_Error(object sender, EventArgs e) 
{ 
    // Code that runs when an unhandled error occurs 
    if (!System.Diagnostics.EventLog.SourceExists("MySource")) 
    { 
     System.Diagnostics.EventLog.CreateEventSource("MySource", 
      "Application"); 
    } 
    System.Diagnostics.EventLog.WriteEntry("MySource", 
     Server.GetLastError().ToString()); 
} 
+0

雖然沒有意識到OP,但事件日誌等方法中的東西並不是必需的 - 您可以隨意處理它。重要的是Global.asax和'Server.GetLastError()'中方法的簽名,它給你最近拋出的異常。 – 2010-09-13 11:17:24

8

使用AppDomainUnhandledException事件:

static void Main(string[] args) 
    { 

     AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); 

    } 

    static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) 
    { 
     // log the exception 
    } 

對於ASP.NET使用您將使用glabal.asax。

0

如果你使用WinForms,你可以看看my other answer related to this。儘管如此,它的確使用了try-catch,因爲我沒有其他方法可以知道。

查看其他答案的ASP.NET和可能的其他.NET使用。