cleansharp.NET
"Clean code always looks like it was written by someone who cares."— Robert C. Martin (Uncle Bob)
When rethrowing exceptions, use throw;
instead of throw ex;
to preserve the original stack trace.
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.
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
}
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
}
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.
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.
throw;
when rethrowing exceptions