#899 – Exception Type Variable in a catch Block Is Optional

In a catch block that specifies a particular exception type to catch, you’ll typically include a named variable representing the exception object that is caught.  Using this variable, code within your handler can access information about the exception that was caught.

            try
            {
                Dog d = new Dog("Kirby", 15);
                d.Bark(BarkSound.Woof, 99);
            }
            catch (DogBarkException dbe)
            {
                Console.WriteLine("Kirby didn't bark properly");
                Console.WriteLine(string.Format("Can't bark {0} times", dbe.NumTimes));
            }

If you don’t need to access data within the exception object, but you still want to catch exceptions of a specific type, you can omit the variable.  This will allow you to catch exceptions of a particular type, but not give you any access of data within the exception object.

            try
            {
                Dog d = new Dog("Kirby", 15);
                d.Bark(BarkSound.Woof, 99);
            }
            catch (DogBarkException)
            {
                Console.WriteLine("Kirby didn't bark properly");
            }
Advertisement

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

One Response to #899 – Exception Type Variable in a catch Block Is Optional

  1. Pingback: Dew Drop – July 31, 2013 (#1,596) | 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: