Re-Throwing Exceptions

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.

Print | posted @ Friday, April 27, 2007 2:05 AM

Comments on this entry:

No comments posted yet.

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 5 and 3 and type the answer here: