#901 – Throwing a New Exception from a catch Block

Within a catch block, you can rethrow the original exception using the throw statement.  This allows any method further up in the call stack to also handle the exception.

There are also cases when you want to throw an exception that is different from the exception that you just caught.  You can do this using the throw new syntax and by storing the original exception in the new exception’s InnerException property.

In the example below, the code in the DoDogStuff method catches a DogBarkException, handles it, and then throws a new (more general) exception.

        static void Main(string[] args)
            catch (Exception xx)
                Console.WriteLine("** Exception in Main():");

        static void DoDogStuff()
                Dog d = new Dog("Kirby", 15);
                d.Bark(BarkSound.Woof, 99);
            catch (DogBarkException xx)
                Console.WriteLine(string.Format("** DogBarkException: Can't bark {0} times!", xx.NumTimes));
                throw new ApplicationException("Failure to do dog stuff", xx);



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

One Response to #901 – Throwing a New Exception from a catch Block

  1. Pingback: Dew Drop – August 2, 2013 (#1,598) | 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 )

Google photo

You are commenting using your Google 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: