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

"catch" clauses should do more than rethrow

    XMLWordPrintable

    Details

    • Message:
      Add logic to this catch clause or eliminate it and rethrow the exception automatically.
    • Default Severity:
      Minor
    • Impact:
      Low
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Targeted languages:
      ABAP, Flex
    • Covered Languages:
      C#, C, C++, Java, JavaScript, Objective-C, PHP, PL/SQL, Python, Swift, T-SQL, TypeScript, VB.Net
    • Irrelevant for Languages:
      Cobol, Go, HTML, PL/I, RPG, VB6, XML
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      5min
    • Analysis Level:
      Syntactic Analysis
    • Analysis Scope:
      Main Sources
    • Common Rule:
      Yes
    • ReSharper:
      RedundantCatchClause
    • TSLint-SonarTS:
      no-useless-catch
    • Quick-fixes:
      Hide

      Remove redundant catch: removes the redundant catch, or if it was the only catch and there is no finally block then the whole try statement is replaced by the statements in the try block.

      Show
      Remove redundant catch: removes the redundant catch, or if it was the only catch and there is no finally block then the whole try statement is replaced by the statements in the try block.

      Description

      A catch clause that only rethrows the caught exception has the same effect as omitting the catch altogether and letting it bubble up automatically, but with more code and the additional detriment of leaving maintainers scratching their heads.

      Such clauses should either be eliminated or populated with the appropriate logic.

      Noncompliant Code Example

      string s = "";
      try
      {
        s = File.ReadAllText(fileName);
      }
      catch (Exception e)  // Noncompliant
      { 
        throw;
      }
      

      Compliant Solution

      string s = "";
      try 
      {
        s = File.ReadAllText(fileName);
      }
      catch (Exception e) // Compliant
      {  
        logger.LogError(e);
        throw;
      }
      

      or

      string s = File.ReadAllText(fileName);
      

        Attachments

          Issue Links

            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: