捕获完全意外的错误

时间:2013-02-08 13:29:45

标签: c# visual-studio-2010 visual-studio error-handling runtime-error

我有一个ErrorRecorder应用程序,它会输出错误报告并询问用户是否要将该报告发送给我。

然后,我有主应用程序。如果发生错误,它会将错误报告写入文件,并要求ErrorRecorder打开该文件以向用户显示错误报告。

所以我使用Try / Catch捕获了大部分错误。

但是,如果出现完全意外的错误并关闭我的程序,该怎么办呢。

是否有全局/覆盖方法或类似的东西,告诉程序“在关闭之前如果发生意外错误,请调用”ErrorRecorderView()“Method”

1 个答案:

答案 0 :(得分:5)

我认为这就是您所追求的 - 您可以在appdomain级别处理异常 - 即在整个程序中处理异常。
http://msdn.microsoft.com/en-GB/library/system.appdomain.unhandledexception.aspx

using System;
using System.Security.Permissions;

public class Test
{

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

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

    throw new Exception("2");

    // Output: 
    //   Catch clause caught : 1 
    //   MyHandler caught : 2
}

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

public static void Main()
{
    Example();
}

}

相关问题