Sometimes you may want to catch an exception using a try/catch block to do some processing, such as record the error to a log file, but then re-throw the exception so that it isn’t suppressed.
I often see this being done like this:
string sourceString = "blah blah"; double result; try { // This will throw an exception... result = double.Parse(sourceString); } catch (Exception ex) { Console.WriteLine("Exception of type " + ex.GetType().ToString() + " occurred: " + ex.Message); throw ex; }
The problem with this is that by calling throw ex you lose the stack trace of the original exception.
The solution is to simply omit the argument to the throw:
string sourceString = "blah blah"; double result; try { // This will throw an exception... result = double.Parse(sourceString); } catch (Exception ex) { Console.WriteLine("Exception of type " + ex.GetType().ToString() + " occurred: " + ex.Message); throw; }
This way the stack trace of the exception is preserved.