Exception Handling 101

There is a lot of very good documentation on how to use Exceptions in .NET. If you don’t want to read these, and you are a programmer and unsure of how to use Exceptions, when to catch them, when to throw, or anything else surrounding the topic of exceptions, my recommendation is for you to do nothing.

The Must Reads are these:

  1. Best Practices for Handling Exceptions http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconbestpracticesforhandlingexceptions.asp?frame=true&hidetoc=true
  2. Error Raising and Handling Guidelines http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp?frame=true&hidetoc=true

 

This is a case where doing nothing is better than doing the wrong thing. If you REALLY feel like you should not crash, and continue if possible, and you just want to display a Message Box that says “ERROR” with a Red X then I give you these lines of code.

static void Main()

{

System.AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

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

...

}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)

{

    MessageBox.Show("An error has occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);

}

static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)

{

    MessageBox.Show("An error has occurred.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);

}

 

Please please please don’t write code like this

 

 

public static void PleaseDoNotCodeLikeThis()

{

    try

    {

        if (batchFileName.Length > 0)

        {

            if (batchArchiveFolderName.Length > 0)

            {

                if (File.Exists(batchFileName))

                {

                    try

                    {

                        DoSomeStuffWithBatchFile();

                    }

                    catch (Exception ex)

                    {

                        throw (new Exception(“Error in batch file. “ + ex.Message));

                    }

                    string sWorkPath = TMP_DIR_PATH;

                    DoSomeOtherStuffWithResultsWhichMayNotExist();

                    if (Directory.Exists(batchArchiveFolderName))

                    {

 

                        sArc = batchSingleRow.outputFileName;

                        sArcPath = batchArchiveFolderName + Path.DirectorySeparatorChar;

                    }

                    else

                        throw (new Exception(“Invalid batch archive folder name.”));

 

 

                    foreach (object myObject in someCollectionOfJunkFromThisBatchStuff)

                    {

                        DoEvenMoreStuffIncludingForkThreadsWriteFilesAndOtherStuff();

                        try

                        {

                        ParsingAndDoingOtherStuffWithFiles();

                        }

                        catch (Exception ex)

                        {

                            DoStuffJoinThreadsCloseFilesWriteErrorLog();

                            continue;

                            //this.Close();

                            //return;

                        }

 

                        DoStuffJoinThreadsCloseFilesWriteErrorLog();

 

                    }

                    if (cnt == batchDataCollection.Count)

                    {

                        WowWeWereCountingAndItLooksLikeWeGotItAllBuildAMessageAndDisplayItToUserOhWellIfItWasNotAllDoneWeLeaveTheUserHanging();

                        MessageBox.Show(arcBatMsg, “Archive”, MessageBoxButtons.OK, MessageBoxIcon.Information);

                        this.Close();

                    }

                }

                else

                {

                    MessageBox.Show(“Error! Invalid batch file specified. “, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Warning);

 

                }

            }

            else

            {

                MessageBox.Show(“Specify a folder for storing the new archives. “, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }

        }

        else

        {

            MessageBox.Show(“Specify a valid file for archiving in batch mode. “, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Warning);

        }

    }

    catch (Exception ex)

    {

        MessageBox.Show(“Batch Archive not created. “ + ex.Message, “Error”, MessageBoxButtons.OK, MessageBoxIcon.Error);

    }

}

If this code looks familiar to you, then you have my deepest sympathy.

If you aren’t sure what is wrong with code like this, then please, seek help.

I should be clear. Each of the longly named methods like DoSomeStuffWithBatchFile and DoSomeOtherStuffWithResultsWhichMayNotExist are of my own creation. This is where I removed between 50-200 or maybe more lines of code from this method. Yes, this is one method. The above has a Maintenence Complexity of 218. The original which I gutted has an MC of 1657. It isn’t even the highest MC in the application. I don’t have to look at the 2188 scored method that is a Windows Form clicked event handler.

 

Current Frustration Level: Moderately High

Current Amusement Level: Very High

Current “Wow, now I understand the frustration of others” Level: Record High

Anyone can write software. It probably won’t be maintainable.

1 thought on “Exception Handling 101”

Comments are closed.