Content

AvoidNestedBlocks

Since Checkstyle 3.1

Description

Finds nested blocks (blocks that are used freely in the code).

Rationale: Nested blocks are often leftovers from the debugging process, they confuse the reader.

For example this Check finds the obsolete braces in

public void guessTheOutput()
{
  int whichIsWhich = 0;
  {
    whichIsWhich = 2;
  }
  System.out.println("value = " + whichIsWhich);
}
        

and debugging / refactoring leftovers such as

// if (conditionThatIsNotUsedAnyLonger)
{
  System.out.println("unconditional");
}
        

A case in a switch statement does not implicitly form a block. Thus to be able to introduce local variables that have case scope it is necessary to open a nested block. This is supported, set the allowInSwitchCase property to true and include all statements of the case in the block.

switch (a)
{
  case 0:
    // Never OK, break outside block
    {
      x = 1;
    }
    break;
  case 1:
    // Never OK, statement outside block
    System.out.println("Hello");
    {
      x = 2;
      break;
    }
  case 2:
    // OK if allowInSwitchCase is true
    {
      System.out.println("Hello");
      x = 3;
      break;
    }
}
        

Properties

name description type default value since
allowInSwitchCase Allow nested blocks if they are the only child of a switch case. Boolean false 3.2

Examples

To configure the check:

<module name="AvoidNestedBlocks"/>
        

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

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;
}
        

This check processes LITERAL_CASE and LITERAL_DEFAULT separately. So, if tokens=LITERAL_DEFAULT, following code will not trigger any violation, as the empty block belongs to LITERAL_CASE:

Configuration:

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

Result:

switch (a) {
  default:        // no violation for "default:" as empty block belong to "case 1:"
  case 1: { }
}
        

Properties

Examples

To configure the check:

<module name="EmptyBlock"/>
        

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

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

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

EmptyCatchBlock

Since Checkstyle 6.4

Description

Checks for empty catch blocks. By default check allows empty catch block with any comment inside.

Notes

There are two options to make validation more precise: exceptionVariableName and commentFormat. If both options are specified - they are applied by any of them is matching.

Properties

name description type default value since
exceptionVariableName Specify the RegExp for the name of the variable associated with exception. If check meets variable name matching specified value - empty block is suppressed. Regular Expression "^$" (empty) 6.4
commentFormat Specify the RegExp for the first comment inside empty catch block. If check meets comment inside empty catch block matching specified format - empty block is suppressed. If it is multi-line comment - only its first line is analyzed. Regular Expression ".*" 6.4

Examples

To configure the check to suppress empty catch block if exception's variable name is expected or ignore or there's any comment inside:

<module name="EmptyCatchBlock">
  <property name="exceptionVariableName" value="expected|ignore"/>
</module>
        

Such empty blocks would be both suppressed:

try {
  throw new RuntimeException();
} catch (RuntimeException expected) {
}
try {
  throw new RuntimeException();
} catch (RuntimeException ignore) {
}
        

To configure the check to suppress empty catch block if single-line comment inside is "//This is expected":

<module name="EmptyCatchBlock">
  <property name="commentFormat" value="This is expected"/>
</module>
        

Such empty block would be suppressed:

try {
  throw new RuntimeException();
} catch (RuntimeException ex) {
  //This is expected
}
        

To configure the check to suppress empty catch block if single-line comment inside is "//This is expected" or exception's variable name is "myException" (any option is matching):

<module name="EmptyCatchBlock">
  <property name="commentFormat" value="This is expected"/>
  <property name="exceptionVariableName" value="myException"/>
</module>
        

Such empty blocks would be suppressed:

try {
  throw new RuntimeException();
} catch (RuntimeException e) {
  //This is expected
}
...
try {
  throw new RuntimeException();
} catch (RuntimeException e) {
  //   This is expected
}
...
try {
  throw new RuntimeException();
} catch (RuntimeException e) {
  // This is expected
  // some another comment
}
...
try {
  throw new RuntimeException();
} catch (RuntimeException e) {
  /* This is expected */
}
...
try {
  throw new RuntimeException();
} catch (RuntimeException e) {
  /*
  *
  * This is expected
  * some another comment
  */
}
...
try {
  throw new RuntimeException();
} catch (RuntimeException myException) {

}
        

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

LeftCurly

Since Checkstyle 3.0

Description

Checks for the placement of left curly braces ('{') for code blocks.

Properties

Examples

To configure the check:

<module name="LeftCurly"/>
        

To configure the check to apply the nl policy to type blocks:

<module name="LeftCurly">
  <property name="option" value="nl"/>
  <property name="tokens" value="CLASS_DEF,INTERFACE_DEF"/>
</module>
        

An example of how to configure the check to validate enum definitions:

<module name="LeftCurly">
  <property name="ignoreEnums" value="false"/>
</module>
        

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

NeedBraces

Since Checkstyle 3.0

Description

Checks for braces around code blocks.

Properties

name description type default value since
allowSingleLineStatement allow single-line statements without braces. Boolean false 6.5
allowEmptyLoopBody allow loops with empty bodies. Boolean false 6.12.1
tokens tokens to check subset of tokens LITERAL_DO, LITERAL_ELSE, LITERAL_FOR, LITERAL_IF, LITERAL_WHILE, LITERAL_CASE, LITERAL_DEFAULT, LAMBDA. LITERAL_DO, LITERAL_ELSE, LITERAL_FOR, LITERAL_IF, LITERAL_WHILE. 3.0

Examples

To configure the check:

<module name="NeedBraces"/>
        

To configure the check for if and else blocks:

<module name="NeedBraces">
  <property name="tokens" value="LITERAL_IF, LITERAL_ELSE"/>
</module>
        

To configure the check to allow single-line statements (if, while, do-while, for) without braces:

<module name="NeedBraces">
  <property name="allowSingleLineStatement" value="true"/>
</module>
        

Next statements won't be violated by check:

if (obj.isValid()) return true; // OK
while (obj.isValid()) return true; // OK
do this.notify(); while (o != null); // OK
for (int i = 0; ; ) this.notify(); // OK
        

To configure the check to allow case, default single-line statements without braces:

<module name="NeedBraces">
  <property name="tokens" value="LITERAL_CASE, LITERAL_DEFAULT"/>
  <property name="allowSingleLineStatement" value="true"/>
</module>
        

Next statements won't be violated by check:

switch (num) {
  case 1: counter++; break; // OK
  case 6: counter += 10; break; // OK
  default: counter = 100; break; // OK
}
        

To configure the check to allow loops (while, for) with empty bodies:

<module name="NeedBraces">
  <property name="allowEmptyLoopBody" value="true"/>
</module>
        

Next statements won't be violated by check:

while (value.incrementValue() < 5); // OK
for(int i = 0; i < 10; value.incrementValue()); // OK
        

To configure the check to lambdas:

<module name="NeedBraces">
  <property name="tokens" value="LAMBDA"/>
  <property name="allowSingleLineStatement" value="true"/>
</module>
          

Results in following:

allowedFuture.addCallback(result -> assertEquals("Invalid response",
  EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS), result), // violation, lambda spans 2 lines
  ex -> fail(ex.getMessage())); // OK

allowedFuture.addCallback(result -> {
  return assertEquals("Invalid response",
    EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS), result);
  }, // OK
  ex -> fail(ex.getMessage()));
          

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

RightCurly

Since Checkstyle 3.0

Description

Checks the placement of right curly braces ('}') for code blocks. This check supports if-else, try-catch-finally blocks, while-loops, for-loops, method definitions, class definitions, constructor definitions, instance, static initialization blocks, annotation definitions and enum definitions. For right curly brace of expression blocks please follow issue #5945.

Properties

name description type default value since
option Specify the policy on placement of a right curly brace ('}'). Right Curly Brace Policy same 3.0
tokens tokens to check subset of tokens LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE, CLASS_DEF, METHOD_DEF, CTOR_DEF, LITERAL_FOR, LITERAL_WHILE, LITERAL_DO, STATIC_INIT, INSTANCE_INIT, ANNOTATION_DEF, ENUM_DEF. LITERAL_TRY, LITERAL_CATCH, LITERAL_FINALLY, LITERAL_IF, LITERAL_ELSE. 3.0

Examples

To configure the check:

<module name="RightCurly"/>
        

To configure the check with policy alone for else and METHOD_DEF tokens:

<module name="RightCurly">
  <property name="option" value="alone"/>
  <property name="tokens" value="LITERAL_ELSE, METHOD_DEF"/>
</module>
        

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