#895 – Catching a Custom Exception Type
July 25, 2013 1 Comment
You might define a custom exception if you want to add custom data to an exception that you throw or if you just want calling code to be able to check for your specific exception.
In the example below, we’ve created a custom exception type, DogBarkException, that we throw when we have a problem in the Dog.Bark method. The exception contains all of the normal data found in an instance of Exception, as well as additional information about the dog and the attempted bark.
try { Dog d = new Dog("Buster", 5); d.Bark(BarkSound.Woof, 12); } catch (DogBarkException xx) { Console.WriteLine(xx.ToString()); Console.WriteLine("Dog {0}, aged {1}, couldn't bark", xx.DogName, xx.DogAge); Console.WriteLine(" Attempted {0} bark, {1} times", xx.BarkSound, xx.BarkNumTimes); }
If we set a breakpoint within the catch block, we can examine the various properties of the DogBarkException object.