#894 – Creating a Custom Exception Type with Custom Data
July 24, 2013 1 Comment
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);
Pingback: Dew Drop – July 24, 2013 (#1,591) | Alvin Ashcraft's Morning Dew