捕获完全意外的错误 [英] Catch completely unexpected error

查看:30
本文介绍了捕获完全意外的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ErrorRecorder 应用程序,它可以打印错误报告并询问用户是否想将该报告发送给我.

I have a ErrorRecorder App, which prints the error report out and asks if the user wants to send that report to me.

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

Then, I have the main app. If an error occurs, It writes the error report to a file and asks ErrorRecorder to open that file to show user the error report.

因此,我使用 Try/Catch 捕获了大部分错误.

So I am catching most of my errors using Try/Catch.

但是,如果发生完全出乎意料的错误并关闭我的程序怎么办.

However, what if an error occurs that was completely unexpected and it shuts down my program.

有没有像全局/覆盖方法或类似的东西,它告诉程序如果发生意外错误,在关闭之前,调用ErrorRecorderView()"方法"

Is there like an Global/Override method or something of that kind, that tells the program "Before shutting down if an unexpected error occurs, call the "ErrorRecorderView()" Method"

推荐答案

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

i think this is what you're after - you can handle exceptions at the appdomain level - i.e. across the whole program.
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();
}

}

这篇关于捕获完全意外的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆