Catch completely unexpected error

2019-01-27 02:44发布

问题:

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

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.

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.

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"

回答1:

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();
}

}