#901 – Throwing a New Exception from a catch Block
August 2, 2013 1 Comment
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) { try { DoDogStuff(); } catch (Exception xx) { Console.WriteLine("** Exception in Main():"); Console.WriteLine(xx.ToString()); } } static void DoDogStuff() { try { 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); } }