rspec/rules/S3877/csharp/rule.adoc

73 lines
2.9 KiB
Plaintext

== Why is this an issue?
The rule is reporting when an exception is thrown from certain methods and constructors. These methods are expected to behave in a specific way and throwing an exception from them can lead to unexpected behavior and break the calling code.
[source,csharp]
----
public override string ToString()
{
if (string.IsNullOrEmpty(Name))
{
throw new ArgumentException(nameof(Name)); // Noncompliant
}
//...
}
----
An issue is raised when an exception is thrown from any of the following:
* https://learn.microsoft.com/en-us/dotnet/api/system.object.tostring[ToString]
* https://learn.microsoft.com/en-us/dotnet/api/system.object.equals[Object.Equals]
* https://learn.microsoft.com/en-us/dotnet/api/system.iequatable-1.equals[IEquatable.Equals]
* https://learn.microsoft.com/en-us/dotnet/api/system.object.gethashcode[GetHashCode]
* https://learn.microsoft.com/en-us/dotnet/api/system.idisposable.dispose[IDisposable.Dispose]
* https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/events/how-to-implement-custom-event-accessors[Event accessors]
* https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors[static constructors]
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/module-initializers[Module initializers]
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/operator-overloading[operators ==, !=, <, >, <=, >=]
* https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/user-defined-conversion-operators[implicit cast operators]
=== Exceptions
Certain exceptions will be ignored in specific contexts, thus not raising the issue:
* `System.NotImplementedException` and its derivatives are ignored for all the aforementioned.
* `System.InvalidOperationException`, `System.NotSupportedException`, and `System.ArgumentException` and their derivatives are ignored in event accessors.
== Resources
=== Documentation
* https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/exceptions/[Exceptions and Exception Handling]
* https://learn.microsoft.com/en-us/dotnet/standard/exceptions/best-practices-for-exceptions[Best practices for exceptions]
* https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1065[CA1065: Do not raise exceptions in unexpected locations]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Remove this "throw" statement.
=== Highlighting
``++throw xxx++``
'''
== Comments And Links
(visible only on this page)
=== on 8 Mar 2017, 14:03:45 Ann Campbell wrote:
FYI [~amaury.leve] our standard is AmE, so double quotes, not single quotes.
=== on 8 Mar 2017, 19:32:18 Ann Campbell wrote:
\[~amaury.leve] did you mean ``++Equals(Object)++`` rather than ``++Object.Equals++``?
endif::env-github,rspecator-view[]