Sunday, August 2, 2009

Throw; versus Throw e;

In Coding Standards is the differents between throw and throw e explained.

What is the difference?
The difference is that 'throw;' the original stack trace persists and 'throw ex' truncates the stack trace after the method where the 'throw ex;' is called.

When using 'throw;'?
When in the try{...} a method is called then you must use 'throw;' to take care that you have the original stack trace.


Example:
// Bad!
catch(Exception ex)
{
Log(ex);
throw ex;
}

// Good!
catch(Exception)
{
Log(ex);
throw;
}

Another alternative is to create a new Exception and pass the current exception as inner exception. The stack trace is shown correctly (complete)


Example:
// Bad!
catch(Exception ex)
{
Log(ex);
throw ex;
}

// Good!
catch(Exception)
{
Log(ex);
Throw new NotImplementedException(“some extra information”, ex);
}

See for more information Fabrice's weblog, Signs on the Sand, Joteke's Blog

No comments:

Post a Comment