Rule Definition
Methods that are not expected to throw exceptions can be categorized as follows:
-Event Accessor Methods
-Equals Methods
-GetHashCode Methods
-ToString Methods
-Static Constructors
-Dispose Methods
-Equality Operators
-Implicit Cast Operators
Limitations:
*The following exceptions can be thrown from a property get method:
System.InvalidOperationException and all derivatives (including System.ObjectDisposedException)
System.NotSupportedException and all derivatives
System.ArgumentException (only from indexed get)
KeyNotFoundException (only from indexed get)
*The following exceptions can be thrown from an event accessor:
System.InvalidOperationException and all derivatives (including System.ObjectDisposedException)
System.NotSupportedException and all derivatives
ArgumentException and derivatives
*The versions of GetHashCode that take an argument can throw an ArgumentException. However, Object.GetHashCode should never throw an exception.
Remediation
Change the logic so that it no longer must throw an exception.
Violation Code Sample
public class Person : IEquatable<Person>
{
public string lName;
public override bool Equals(Object obj)
{
Person pers = obj as Person;
if (pers == null)
throw new ArgumentException("..."); //VIOLATION
else
return (this.lName== pers.lName);
}
}
Fixed Code Sample
public class Person : IEquatable<Person>
{
public string lName;
public override bool Equals(Object obj)
{
Person pers = obj as Person;
if (pers == null)
return false; // Compliant
else
return (this.lName== pers.lName);
}
}
Reference
https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1065
Related Technologies
Technical Criterion
Programming Practices - Error and Exception Handling
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.