#883 – Re-throwing an Exception
July 9, 2013 6 Comments
When you catch an exception in an exception handler, you have the option of executing some code and then re-throwing the exception. When you re-throw an exception from a handler, code that called the current method has the option of also handling the exception. Alternatively, if no higher-level handler exists, the exception will be treated as an unhandled exception after you re-throw it.
In the example below, DoSomeStuff catches all exceptions, writes information to a log file and then re-throws the exception.
private const string MyLogFile = "App1.log"; static void Main(string[] args) { Console.WriteLine("About to do some stuff"); try { DoSomeStuff(); } catch (Exception xx) { Console.WriteLine(xx.ToString()); } Console.ReadLine(); } static void DoSomeStuff() { try { Dog d1 = new Dog("Jack", 15); Dog d2 = new Dog("Kirby", 150); } catch (Exception xx) { StreamWriter sw = new StreamWriter(MyLogFile, true); // append sw.WriteLine(string.Format("Exception at {0}", DateTime.Now)); sw.WriteLine(xx.ToString()); sw.Close(); throw; // Re-throw } }
Pingback: Dew Drop – July 9, 2013 (#1,581) | Alvin Ashcraft's Morning Dew
Pingback: #884 – Things You Might Do in an Exception Handler | 2,000 Things You Should Know About C#
Catch blocks that merely rethrow a caught exception wrapped inside a new instance of the same type only add to code size and runtime complexity.
Pingback: #900 – What the Exception Object Contains when You Re-throw an Exception | 2,000 Things You Should Know About C#
Pingback: #901 – Throwing a New Exception from a catch Block | 2,000 Things You Should Know About C#
Pingback: #911 – finally Block Execution When Exception Is Rethrown | 2,000 Things You Should Know About C#