C# – Throwing Exceptions best practices

Many people questioned themselves about which of the two forms is the best to (re) throw an exception?

Is it better to do this :

try
{
    ...
}
catch (Exception ex)
{
    ...
    throw;
}

or this:

try
{
    ...
}
catch (Exception ex)
{
    ...
    throw ex;
}

The way to preserve the stack trace is through the use of the throw; This is valid as well

try {
  // something that boms here
} catch (Exception ex)
{
    throw;
}

throw ex; is basically like throwing an exception from that point, so the stack trace would only go to where you are issuing the throw ex; statement.

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
    }
}

Thus, “throw;” it is the prefered way instead of “throw ex;

However, another option is shown below:

try
{
} 
catch(Exception ex)
{
     throw new MoreDescriptiveException("here is what was happening", ex);
}

wich is valid too. In this case the original Exception is passed as an argument to the new instance.

Do prefer using an empty throw when catching and re-throwing an exception. This is the best way to preserve the exception call stack.

Share            
X
                                                                                                        

Leave a Reply

Your email address will not be published. Required fields are marked *