You may want to catch and re-throw an exception for any number of reasons, one of the most common being to log some details about the exception but still let it propagate out to the calling code.
I often see this being done as follows:
try
{
DoStuff();
}
catch (Exception ex)
{
Logger.Log(ex);
throw ex;
}
The problem with the above code is in the line where we re-throw the exception:
throw ex;
When an exception is thrown by reference it has its stack trace filled in - in this case that means that the original stack trace about where the exception occurred will be overwritten with a stack trace pointing to this line.
When you are in a catch block you can write the following instead:
throw;
This will cause the original exception that we caught to be re-thrown but will leave its stack trace as it was. This means that if we look at the exception higher up we will get an accurate picture of what went wrong.