EmptyBlock

Since Checkstyle 3.0

Description

Checks for empty blocks. This check does not validate sequential blocks.

Sequential blocks won't be checked. Also, no violations for fallthrough:

switch (a) {
  case 1:                          // no violation
  case 2:                          // no violation
  case 3: someMethod(); { }        // no violation
  default: break;
}
        

NOTE: This check processes LITERAL_CASE and LITERAL_DEFAULT separately. Verification empty block is done for single nearest {@code case} or {@code default}.

Properties

Examples

To configure the check:

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

Example:

public class Example1 {
  private void emptyLoop() {
    for (int i = 0; i < 10; i++) { // violation 'Must have at least one statement'
    }

    try { // violation 'Must have at least one statement'

    } catch (Exception e) {
      // ignored
    }
  }
}
        

To configure the check for the text policy and only try blocks:

<module name="Checker">
  <module name="TreeWalker">
    <module name="EmptyBlock">
      <property name="option" value="text"/>
      <property name="tokens" value="LITERAL_TRY"/>
    </module>
  </module>
</module>
        

Example:

public class Example2 {
  private void emptyLoop() {
    for (int i = 0; i < 10; i++) {
      // ignored
    }

    try {
    }  // violation above 'Empty try block'
    catch (Exception e) {
      // ignored
    }
  }
}
        

To configure the check for default in switch block:

<module name="Checker">
  <module name="TreeWalker">
    <module name="EmptyBlock">
      <property name="tokens" value="LITERAL_DEFAULT"/>
    </module>
  </module>
</module>
        

Example:

public class Example3 {
  private void test(int a) {
    switch (a) {
      case 1: someMethod();
      default: // OK, as there is no block
    }
    switch (a) {
      case 1: someMethod();
      default: {} // violation 'Must have at least one statement'
    }
  }
}
        

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.blocks

Parent Module

TreeWalker