Peter Goodman bio photo

Peter Goodman

A developer living in Auckland building software using all sorts of bits and pieces I find along the way. Originally from Northern Ireland.

Twitter Google+ LinkedIn Github

I was going over some old code recently to try to resolve a production issue. The log of the stack trace was not providing enough information on the thrown exception and it reminded me of a good tip for throwing and specifically re-throwing exceptions.

Consider the following code:

 

try
{
  int x = 0;
  int y = 5 / x;
}
catch (Exception ex)
{
 
throw ex;
}

The stack trace at the time that the DivisionByZero is thrown will be different from the rethrow in the catch block. This is because the "throw ex" will create a new exception and throw it. Instead, you should try to use the code below.

try
{
 
int x = 0;
 
int y = x / 5;
}
catch (Exception ex)
{
 
throw;
}

In this case the original exception will be thrown with the correct stack trace. Of course wrapping the exception before it is thrown will also preserve the stack trace.