NoGetMessageInThrow

Since Checkstyle 13.3.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="NoGetMessageInThrow"/>
  </module>
</module>

Example:


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

  void method2() throws IOException {
    try {
      throw new IOException();
    } catch (IOException ex) {
      // OK, provides context without redundant message
      throw new IllegalStateException("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.

Package

com.puppycrawl.tools.checkstyle.checks.coding

Parent Module

TreeWalker