#893 – A Custom Exception Type Doesn’t Need to Add Custom Data

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);
            }

893-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #893 – A Custom Exception Type Doesn’t Need to Add Custom Data

  1. Pingback: #894 – Creating a Custom Exception Type with Custom Data | 2,000 Things You Should Know About C#

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 )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: