CA1032: Implement standard exception constructors
Property | Value |
---|---|
Rule ID | CA1032 |
Title | Implement standard exception constructors |
Category | Design |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 8 | No |
Cause
A type extends System.Exception but doesn't declare all the required constructors.
Rule description
Exception types must implement the following three public constructors:
public NewException()
public NewException(string)
public NewException(string, Exception)
Failure to provide the full set of constructors can make it difficult to correctly handle exceptions. For example, the constructor that has the signature NewException(string, Exception)
is used to create exceptions that are caused by other exceptions. Without this constructor, you can't create and throw an instance of your custom exception that contains an inner (nested) exception, which is what managed code should do in such a situation.
For more information, see CA2229: Implement serialization constructors.
How to fix violations
To fix a violation of this rule, add the missing constructors to the exception, and make sure that they have the correct accessibility.
When to suppress warnings
It's safe to suppress a warning from this rule when the violation is caused by using a different access level for the public constructors.
Suppress a warning
If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable CA1032
// The code that's violating the rule is on this line.
#pragma warning restore CA1032
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1032.severity = none
For more information, see How to suppress code analysis warnings.
Example
The following example contains an exception type that violates this rule and an exception type that is correctly implemented.
// Violates rule ImplementStandardExceptionConstructors.
public class BadException : Exception
{
public BadException()
{
// Add any type-specific logic, and supply the default message.
}
}
[Serializable()]
public class GoodException : Exception
{
public GoodException()
{
// Add any type-specific logic, and supply the default message.
}
public GoodException(string message) : base(message)
{
// Add any type-specific logic.
}
public GoodException(string message, Exception innerException) :
base(message, innerException)
{
// Add any type-specific logic for inner exceptions.
}
}