#894 – Creating a Custom Exception Type with Custom Data

You might create a custom exception type that doesn’t extend the base Exception type.  But quite often it’s useful to add some additional data that is specific to your exception type.

In the example below, we create a new exception type that stores two additional fields related to the Dog.Bark operation that failed.

    public enum BarkSound { Yip, Arf, Woof };

    public class DogBarkException : Exception
    {
        public DogBarkException()
        {
        }

        public DogBarkException(string message)
            : base(message)
        {
        }

        public DogBarkException(string message, Exception innerException)
            : base(message, innerException)
        {
        }

        public BarkSound Sound { get; set; }
        public int NumTimes { get; set; }

        public DogBarkException(string message, BarkSound sound, int numTimes)
            : base(message)
        {
            Sound = sound;
            NumTimes = numTimes;
        }
    }

We can now throw a new instance of this exception type as follows:

            if ((barkSound == BarkSound.Woof) && (numTimes > 5))
                throw new DogBarkException("Dogs can't woof more than 3 times in a row", barkSound, numTimes);
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #894 – Creating a Custom Exception Type with Custom Data

  1. Pingback: Dew Drop – July 24, 2013 (#1,591) | Alvin Ashcraft's Morning Dew

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: