EmptyBlock

Since Checkstyle 3.0

Description

Checks for empty blocks.

This check does not validate sequential blocks. This check does not violate fallthrough.

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 case and default in switch block:

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

Example:

public class Example3 {

private void testBadSwitchStatement(int a) {
switch (a) {
case 1 : { } // violation, 'Must have at least one statement'
// the second empty block is 'sequential', skipped.
// violation below, 'Must have at least one statement'
case 2: {} {};
// violation below, 'Must have at least one statement'
case 3: {} {System.out.println();}
// the second empty block is 'sequential', skipped.
case 4: {System.out.println();} {}
default : { } // violation, 'Must have at least one statement'
}
}

private void testGoodSwitchStatement(int a) {
switch (a) {
case 1: { someMethod(); }
default: { someMethod(); }
}
switch (a) {
case 1: { someMethod(); }
default: // OK, as there is no block
}
}

private void testBadSwitchRule(int a) {
switch (a) {
case 1 -> { } // violation, 'Must have at least one statement'
default -> { } // violation, 'Must have at least one statement'
}
}

private void testGoodSwitchRule(int a) {
switch (a) {
case 1 -> { someMethod(); }
default -> { someMethod(); }
}
}

void someMethod() { }
}

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