Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
659 views
in Technique[技术] by (71.8m points)

c# - Catch completely unexpected error

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"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...