2016-10-17 119 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 –