"Clean code always looks like it was written by someone who cares."
— Robert C. Martin (Uncle Bob)

Rethrow Exception Correctly

✅ One-liner Summary

When rethrowing exceptions, use throw; instead of throw ex; to preserve the original stack trace.

💡 Short Explanation

Using throw ex; resets the stack trace, making debugging harder by losing the original exception’s context.
Using throw; preserves the complete stack trace, making it easier to track down the root cause of issues.

🚫 Bad Example

This code loses the original stack trace, making debugging more difficult:

try
{
    // Some code that might throw
}
catch (Exception ex)
{
    log.Error("Something went wrong", ex);
    throw ex; // ⚠️ Stack trace is reset here
}

✅ Good Example

This code preserves the original stack trace, making debugging easier:

try
{
    // Some code that might throw
}
catch (Exception ex)
{
    log.Error("Something went wrong", ex);
    throw; // ✅ Original stack trace is preserved
}

💬 Real-World Insight

In production environments, having the complete stack trace is crucial for quick issue resolution.
When using throw ex;, you might spend hours trying to find where an exception originated, only to realize the stack trace was truncated at the catch block.

🛠️ Implementation Guide

To enforce this rule in your project, add the following to your .editorconfig file:

dotnet_diagnostic.CA2200.severity = error

This will prevent developers from using throw ex; instead of throw;, helping maintain better exception handling practices across your team.

🧠 Key Takeaways

  • Always use throw; when rethrowing exceptions
  • Preserves the original stack trace
  • Makes debugging and error tracking much easier
  • Helps maintain the exception’s context through the call stack