#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());
        }
Advertisements