All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.squidjava.rules.squid.S1166.html Maven / Gradle / Ivy

When handling a caught exception, two mandatory informations should be logged:

  • Some context to ease the reproduction of the issue.
  • The original's exception, for its message and stack trace.

Noncompliant Code Example

 // Noncompliant - exception is lost
try { /* ... */ } catch (Exception e) { LOGGER.info("context"); }

// Noncompliant - context is required
try { /* ... */ } catch (Exception e) { LOGGER.info(e); }

// Noncompliant - exception is lost (only message is preserved)
try { /* ... */ } catch (Exception e) { LOGGER.info(e.getMessage()); }

// Noncompliant - exception is lost
try { /* ... */ } catch (Exception e) { throw new RuntimeException("context"); }

Compliant Solution

try { /* ... */ } catch (Exception e) { LOGGER.info("context", e); }

try { /* ... */ } catch (Exception e) { throw new RuntimeException("context", e); }

Exceptions

It is allowed to let the exception propagate.

try {
  /* ... */
} catch (RuntimeException e) {
  doSomething();
  throw e;
} catch (Exception e) {
  // Conversion into unchecked exception is also allowed
  throw new RuntimeException(e);
}

InterruptedException, NumberFormatException, ParseException and MalformedURLException exceptions are arguably used to indicate nonexceptional outcomes. As they are part of Java, developers have no choice but to deal with them. This rule does not verify that those particular exceptions are correctly handled.

int myInteger;
try {
  myInteger = Integer.parseInt(myString);
} catch (NumberFormatException e) {
  // It is perfectly acceptable to not handle "e" here
  myInteger = 0;
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy