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

Exceptions should not be explicitly rethrown

    XMLWordPrintable

    Details

    • Message:
      Use "throw;" instead of "throw xxx;" to preserve the stack trace.
    • Highlighting:
      Hide

      The whole "throw exc;" statement

      Show
      The whole "throw exc;" statement
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      C#
    • Irrelevant for Languages:
      Python
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      2min
    • Analysis Scope:
      Main Sources
    • FxCop:
      RethrowToPreserveStackDetails, CA2200
    • ReSharper:
      PossibleIntendedRethrow

      Description

      When rethrowing an exception, you should do it by simply calling throw; and not throw exc;, because the stack trace is reset with the second syntax, making debugging a lot harder.

      Noncompliant Code Example

      try
      {}
      catch(ExceptionType1 exc)
      {
        Console.WriteLine(exc);
        throw exc; // Noncompliant; stacktrace is reset
      }
      catch (ExceptionType2 exc) 
      {
        throw new Exception("My custom message", exc);  // Compliant; stack trace preserved
      }
      

      Compliant Solution

      try
      {}
      catch(ExceptionType1 exc)
      {
        Console.WriteLine(exc);
        throw;
      }
      catch (ExceptionType2 exc) 
      {
        throw new Exception("My custom message", exc);
      }
      

        Attachments

          Activity

            People

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

              Dates

              Created:
              Updated: