Home

Implementing Custom Exceptions in C# 4.8 Avg (5 ratings)

rate email bookmark Print del.icio.us technorati stumbleupon simpy

Add intelligent exception handling with custom exceptions

Exceptions are the bane of a coder's existence. We can spend days and days testing our applications and processes doing every possible idiotic thing we can think of to break it. Once when our confidence is up and we green light a move to production, BOOM! One of the users out-idiotted us and broke the app on their first try! What happens next is ugly as we try relentlessly trying to track down the bug and fix it before the boss gives us the brow beat-down. It's bad enough we have to deal with the wrath of the boss and an angry customer, but to top it all off we have to deal with the pressure of finding and fixing the bug ASAP!


Custom exception handlers can make tracking down bugs easier, as well as add a layer to elegantly handle bad user requests and known possible conflicts. We'll explore a simple and easy way to create custom exceptions and how to handle them. Oh, and the mantra for exceptions should be that an exception should only be thrown when we can NOT handle it gracefully! For example, you never want to throw an error if the user enters a bad character into an input field. Instead you should either be restricting the input and displaying friendly instructions messages to the user or you should be stripping bad data behind the scenes. Anyway, here is how to set up custom exceptions.

The Custom Exceptions Class

public class CustomExceptions
{
    // Base exception which all custom exceptions should inherit from
    public class BaseStepException : ApplicationException
    {
        private string _customMessage;

        // Gets or Sets the custom error message detailing the error
        public string CustomMessage
        {
            get {return this._customMessage;}
            set {this._customMessage = value;}
        }
    }

    // Exception resulting from a failure in the FTP cleanup process
    public class FTPCleanupException : BaseStepException
    {
        // Constructor (default error message)
        public FTPCleanupException()
        {
            this.CustomMessage = "Exception cleaning-up the temporary files in the FTP process.";
        }

        /// Overloaded constructor (initialize custom error message)
        public FTPCleanupException(string strCustomMessage)
        {
            this.CustomMessage = strCustomMessage;
        }
    }
}

Throwing the custom exception

//An error occurred in the cleanup process. Since the report was already FTP'd to the
//user with success, throw the custom exception to clean up the files via the admin
//panel (manual process)
throw new CustomExceptions.FTPCleanupException("Cleanup of FTP files failed.");

Catching and handling the custom exception

try
{
    ... CODE PROCESS OMMITTED FOR CLARITY ...
}
catch (CustomExceptions.FTPCleanupException ftx)
{
    //Log the failure to file
    Utilities.LogEntry(OutputLog.EmailLog, FileCompletionLogEntry(oReport, ftx.CustomMessage));

    //FTP exception, so mark the files for manual purging and tag it with the error message
    MarkReportForManualPurge(oReport, ftx.CustomMessage);
}

As you can see, it's very simple to create and handle custom exceptions. You create your base class for all custom exceptions to inherit from and then throw the exception at the appropriate time. Once handled, you can do anything you want! In the example we log the error to a file and then tag a failed report for manual purging by an administrative UI. Just apply to your own websites and applications and you'll make your life a little easier.

More information


David Nicolosi
Drop-In Code
Back to index