Re-throwing exceptions in .NET

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.

 
software_development/dotnet/rethrowing_exceptions.txt · Last modified: 2008/04/08 12:10 (external edit)
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki