What is the proper way to re-throw an exception in C#?
You should always use following syntax to rethrow an exception, else you'll stomp the stack trace:
throw;
If you print the trace resulting from "throw ex", you'll see that it ends on that statement and not at the real source of the exception.
Basically, it should be deemed a criminal offense to use "throw ex".
My preferences is to use
try
{
}
catch (Exception ex)
{
...
throw new Exception ("Put more context here", ex)
}
This preserves the original error, but allows you to put more context, such as an object ID, a connection string, stuff like that. Often my exception reporting tool will have 5 chained exceptions to report, each reporting more detail.
If you throw an exception without a variable (the second example) the StackTrace will include the original method that threw the exception.
In the first example the StackTrace will be changed to reflect the current method.
Example:
static string ReadAFile(string fileName) {
string result = string.Empty;
try {
result = File.ReadAllLines(fileName);
} catch(Exception ex) {
throw ex; // This will show ReadAFile in the StackTrace
throw; // This will show ReadAllLines in the StackTrace
}