Exceptions must be thrown

Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

Metadata

ID: csharp-best-practices/exception-must-be-thrown

Language: C#

Severity: Warning

Category: Best Practices

Description

Exceptions should be thrown and not just created. An expression such as new Exception(...) does not throw the exception. You should use the keyword throw to throw the exception`.

Learn More

Non-Compliant Code Examples

using System.Xml;

class MyClass {
    public void myMethod()
    {
        var a = new MyException("something bad happened");
    }
}

Compliant Code Examples

using System.Xml;

class MyClass {
    public void myMethod()
    {
        var bla = new MyClass("something bad happened");
    }
    public void foo() {
            Formatter formatter = language switch
            {
                SqlLanguage.Sql => new StandardSqlFormatter(),
                SqlLanguage.Tsql => new TSqlFormatter(),
                SqlLanguage.Spark => new SparkSqlFormatter(),
                SqlLanguage.RedShift => new RedshiftFormatter(),
                SqlLanguage.PostgreSql => new PostgreSqlFormatter(),
                SqlLanguage.PlSql => new PlSqlFormatter(),
                SqlLanguage.N1ql => new N1qlFormatter(),
                SqlLanguage.MySql => new MySqlFormatter(),
                SqlLanguage.MariaDb => new MariaDbFormatter(),
                SqlLanguage.Db2 => new Db2Formatter(),
                _ => throw new NotSupportedException(),
            };
    }
}
using System.Xml;

class MyClass {
    public void myMethod()
    {
        throw new MyException("something bad happened");
    }
}
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 Analysis