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

Exceptions should be either logged or rethrown but not both

    XMLWordPrintable

    Details

    • Message:
      Either log this exception and handle it, or rethrow it with some contextual information.
    • Highlighting:
      Hide
      • Primary: The exception caught
      • Secondary 1: The logging statement:
        • message: 'Logging statement.'
      • Secondary 2: The throw statement
        • message: 'Thrown exception.'
      Show
      Primary: The exception caught Secondary 1: The logging statement: message: 'Logging statement.' Secondary 2: The throw statement message: 'Thrown exception.'
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Targeted languages:
      C#, C++, Flex, Objective-C, PHP, Python, VB.Net
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      15min

      Description

      In applications where the accepted practice is to log an Exception and then rethrow it, you end up with miles-long logs that contain multiple instances of the same exception. In multi-threaded applications debugging this type of log can be particularly hellish because messages from other threads will be interwoven with the repetitions of the logged-and-thrown Exception. Instead, exceptions should be either logged or rethrown, not both.

      Noncompliant Code Example

      catch (SQLException e) {
        ...
        LOGGER.log(Level.ERROR,  contextInfo, e);
        throw new MySQLException(contextInfo, e);
      }
      

      Compliant Solution

      catch (SQLException e) {
        ...
        throw new MySQLException(contextInfo, e);
      }
      

      or

      catch (SQLException e) {
        ...
        LOGGER.log(Level.ERROR,  contextInfo, e);
        // handle exception...
      }
      

        Attachments

          Issue Links

            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: