NoCauseGetMessageInExceptionConstructor

Since Checkstyle 14.4.0

Description

Checks that throw statements within catch blocks do not use the caught exception's getMessage() call when the thrown exception is the same type as the caught exception, as rethrowing the same exception type with its own message is redundant.

Rationale: When throwing an exception of the same type as the caught exception and including the caught exception's message via getMessage(), the information is redundant. The original exception should be rethrown directly, or a different exception type should be used.

Example of violations:


catch (IOException ex) {
    throw new IOException("Error: " + ex.getMessage()); // violation
}
        

Correct usage:


catch (IOException ex) {
    throw new RuntimeException("Error: " + ex.getMessage(), ex); // OK, different type
}
catch (IOException ex) {
    throw new IOException("Error processing file", ex); // OK, no getMessage()
}
        

Examples

To configure the check:


<module name="Checker">
  <module name="TreeWalker">
    <module name="NoCauseGetMessageInExceptionConstructor"/>
  </module>
</module>

Example:


class Example1 {
  void method1() throws IOException {
    try {
      throw new IOException();
    } catch (IOException ex) {
      // violation below, 'ex.getMessage()' is redundant
      throw new IOException("Error: " + ex.getMessage(), ex);
    }
  }

  void method2() throws IOException {
    try {
      throw new IOException();
    } catch (IOException ex) {
      // OK, different thrown type
      throw new IllegalStateException("Error: " + ex.getMessage(), ex);
    }
  }

  void method3() throws IOException {
    try {
      throw new IOException();
    } catch (IOException ex) {
      // OK, no getMessage() on caught exception
      throw new IOException("Error processing file", ex);
    }
  }
}

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Fully Qualified Name

com.puppycrawl.tools.checkstyle.checks.coding. NoCauseGetMessageInExceptionConstructorCheck

Use this fully qualified class name in configuration when an exact class reference is required.

Parent Module

TreeWalker