Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-2372

Exceptions should not be thrown from property getters

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Remove the exception throwing from this property getter, or refactor the property into a method.
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Legacy Key:
      ThrowFromPropertyGetter
    • Targeted languages:
      JavaScript, TypeScript
    • Covered Languages:
      C#, VB.Net
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      20min
    • Analysis Scope:
      Main Sources
    • FxCop:
      DoNotRaiseExceptionsInUnexpectedLocations, CA1065
    • MSFT Roslyn:
      CA1065

      Description

      Property getters should be simple operations that are always safe to call. If exceptions need to be thrown, it is best to convert the property to a method.

      It is valid to throw exceptions from indexed property getters and from property setters, which are not detected by this rule.

      Noncompliant Code Example

      Module Module1
          Public Property Foo() As Integer
              Get
                  Throw New Exception  ' Non-Compliant
              End Get
              Set(ByVal value As Integer)
                  ' ... some code ...
              End Set
          End Property
      End Module
      

      Compliant Solution

      Module Module1
          Sub SetFoo(ByVal value As Integer)         ' Compliant
              ' ... some code ...
          End Sub
      End Module
      

      Exceptions

      No issue is raised when the thrown exception derives from or is of type NotImplementedException, NotSupportedException or InvalidOperationException.

        Attachments

        1.
        C# RSPEC-3793 Language-Specification Active Unassigned

          Activity

            People

            Assignee:
            Unassigned Unassigned
            Reporter:
            ann.campbell.2 Ann Campbell
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Dates

              Created:
              Updated: