#893 – A Custom Exception Type Doesn’t Need to Add Custom Data
July 23, 2013 1 Comment
You may sometimes define a custom exception type without adding any additional data to the base Exception type. This can still add value, because calling code can now explicitly check for your new exception type. In this way, you’re not adding custom data to the exception that you throw, but you’re adding information by indicating the specific type of exception that occurred.
Assume that we’ve defined a DogBarkException type, which can be thrown by the Dog.Bark method. We can then check for this exception when calling Dog.Bark.
try { Dog d = new Dog("Buster", 5); d.Bark(Dog.BarkSound.Woof, 6); } catch (DogBarkException xx) { Console.WriteLine("Problem with barking!"); Console.WriteLine(xx.Message); } catch (Exception xx) { Console.WriteLine("Something went wrong:"); Console.WriteLine(xx); }