#892 – Creating a Custom Exception Type

You can define a custom exception type when you want to provide error information specific to your application or when you want calling code to be able to detect your custom exception.

You can create a custom exception type by deriving from the Exception class.  Below, we define a new exception type that provides the three most common types of constructors.

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

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

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

We can throw an instance of the new exception type from a Dog.Bark method.

        public enum BarkSound { Yip, Arf, Woof };

        // Dog barks
        public void Bark(BarkSound barkSound, int numTimes)
        {
            if ((barkSound == BarkSound.Woof) && (numTimes > 5))
                throw new DogBarkException("Dogs can't woof more than 3 times in a row");

            for (int i = 0; i < numTimes; i++)
                Console.WriteLine(barkSound.ToString());
        }
Advertisement

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

3 Responses to #892 – Creating a Custom Exception Type

  1. Pingback: #893 – A Custom Exception Type Doesn’t Need to Add Custom Data | 2,000 Things You Should Know About C#

  2. Pingback: #894 – Creating a Custom Exception Type with Custom Data | 2,000 Things You Should Know About C#

  3. Pingback: #895 – Catching a Custom Exception Type | 2,000 Things You Should Know About C#

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 )

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

%d bloggers like this: