user1423893
user1423893

Reputation: 796

Creating an error message that reports a crash from anywhere inside an C# application

I have an executable that is written in C# which runs fine on one computer but crashes without providing an error on another computer.

Is there a class that I can add to my code that will dump all the information relating to the crash no matter where the error occurs within the code?

I have seen this post but I was hoping to create a "catch all" error handling class that would exist in my code.

Upvotes: 0

Views: 195

Answers (1)

Ian Newson
Ian Newson

Reputation: 7949

Try the AppDomain exception handler:

http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

Code sample:

class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            var thr = new Thread(() =>
            {
                Thread.Sleep(1000);
                throw new Exception("Custom exception from thread");
            });
            thr.Start();
            thr.Join();

            Console.WriteLine("Done");
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            //Log information from e.ExceptionObject here
        }
    }

In this example a custom global exception handler is registered, and then a thread is started which throws an exception after 1 second. The global exception handler is then invoked, with the custom exception that has been thrown.

Upvotes: 2

Related Questions