#895 – Catching a Custom Exception Type

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.

                Dog d = new Dog("Buster", 5);
                d.Bark(BarkSound.Woof, 12);
            catch (DogBarkException xx)
                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.



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

One Response to #895 – Catching a Custom Exception Type

  1. Pingback: Dew Drop – July 25, 2013 (#1,592) | Alvin Ashcraft's Morning Dew

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: