2016-10-17 116 views
-5

我使用的示例代碼是this MSDN article.NET未處理的異常

[SecurityPermission(SecurityAction.Demand, Flags=SecurityPermissionFlag.ControlAppDomain)] 
    public static void Main() 
    { 
     AppDomain currentDomain = AppDomain.CurrentDomain; 
     currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler); 

     try { 
     throw new Exception("1"); 
     } catch (Exception e) { 
     Console.WriteLine("Catch clause caught : {0} \n", e.Message); 
     } 

     throw new Exception("2"); 
    } 

    static void MyHandler(object sender, UnhandledExceptionEventArgs args) 
    { 
     Exception e = (Exception) args.ExceptionObject; 
     Console.WriteLine("MyHandler caught : " + e.Message); 
     Console.WriteLine("Runtime terminating: {0}", args.IsTerminating); 
    } 

該處理程序捕獲未處理的異常。但是,在處理程序運行後,未處理的異常2仍然顯示。在調試模式下,在發佈模式下以及是否直接啓動.exe。

我想壓制第二個異常,所以未處理的異常處理程序可以終止/重新啓動應用程序。我記得使用VB.NET在.NET 3中工作。

+7

請將代碼發佈在您的帖子中。鏈接到代碼很難遵循和回覆。 – Hank

+1

你應該更努力地尋找模式。如果'try catch'有助於例外#1,那麼猜猜對於例外#2 ...會有什麼幫助? –

回答

2

見你的問題的鏈接代碼:

// The example displays the following output: 
//  Catch clause caught : 1 
//  
//  MyHandler caught : 2 
//  Runtime terminating: True 
//  
//  Unhandled Exception: System.Exception: 2 
//   at Example.Main() 

正如你所看到的,沒有人處理的第二個例外。引用文章:

此事件提供未捕獲異常的通知。它允許應用程序在系統默認處理程序向用戶報告異常並終止應用程序之前記錄有關異常的信息。

+0

我問是否有人知道如何恢復舊的行爲,允許從任何域默默處理未處理的異常。用戶不應該看到第二個異常,因爲它是未處理的。 –

+0

我還記得有/有一個配置對話框來改變異常行爲(至少在VB.NET中)。目前我找不到它。也許它消失了。 –

+1

@HerbertFeichtinger也許你是指這個? http://stackoverflow.com/a/5762806/3932049 –