Why so brittle?

C# has inherited a brittleness from the Visual C++ world.

By default an unhandled exception in any application will kill an application and return an exception trace even in a windows form.

In Delphi in a forms application the exception shows as a message box.

The assumption in Visual C++ and then C# is that an unhandled exception could result in data corruption so you must shut down now. The assumption in delphi is that some error has occoured.

It is possible to add simple code to emulate the Delphi behavior

// Add the following to your uses clause:
using System.Threading;

//In your main method before run implement the following

Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(new CustomExceptionHandler().OnThreadException);

// Here is the exception handler (in production code use something more elegant, but for development this is fine:

        // Creates a class to handle the exception event.
        internal class CustomExceptionHandler
        {
 
            //Handles the exception event
            public void OnThreadException(object sender, ThreadExceptionEventArgs t)
            {
                DialogResult result = DialogResult.Cancel;
                try
                {
                    result = this.ShowThreadExceptionDialog(t.Exception);
                }
                catch
                {
                    try
                    {
                        MessageBox.Show(“Fatal Error”, “Fatal Error”,
                            MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
                    }
                    finally
                    {
                        Application.Exit();
                    }
                }
 
                // Exits the program when the user clicks Abort.
                if (result == DialogResult.Abort)
                    Application.Exit();
            }
 
            // Creates the error message and display it.
            private DialogResult ShowThreadExceptionDialog(Exception e)
            {
                string errorMsg = “An error occurred please contact the adminstrator ” +
                    “with the following information: “;
                errorMsg = errorMsg + e.Message + ” Stack Trace: ” + e.StackTrace;
                return MessageBox.Show(errorMsg, “Application Error”,
                    MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
            }
        }

    }

However this should be the default behaviour.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s