Metadata

ID: csharp-best-practices/do-not-rethrow

Language: C#

Severity: Warning

Category: Best Practices

Description

The rule “Do not rethrow exception” advises against rethrowing an exception using the throw ex; syntax. This practice is discouraged because it resets the stack trace of the original exception to the current catch block, which can lead to loss of valuable debugging information.

The importance of this rule lies in maintaining the integrity of exception stack traces. These traces provide crucial information about the sequence of method calls that led to the exception, making it easier to locate and fix the source of the error.

How to Remediate

To fix this issue, use the throw; statement without an exception object in catch blocks to rethrow the original exception while preserving its stack trace. For example, replace throw ex; with just throw;. This ensures that the original exception’s stack trace is maintained and aids in effective debugging.

Non-Compliant Code Examples

class Foo {
    public void Bar() {
        try {
            myMethod();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        catch (Exception ex2)
        {
            if (foo) {
                throw ex2;
            }

        }
    }
}

Compliant Code Examples

class Foo {
    public void Bar() {
        try {
            myMethod();
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security

PREVIEWING: guillaume.barrier/ERRORT-5095-general-doc-update