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.

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:

public void foo() {
  int myInteger = 0;
  {                      // violation
    myInteger = 2;
  }
  System.out.println("myInteger = " + myInteger);

  switch (a) {
    case 1:
      {                    // violation
        System.out.println("Case 1");
        break;
      }
    case 2:
      System.out.println("Case 2");     // OK
      break;
  }
}
        

To configure the check to allow nested blocks in switch case:

<module name="AvoidNestedBlocks">
  <property name="allowInSwitchCase" value="true"/>
</module>
        

Example:

public void foo() {
  int myInteger = 0;
  {                      // violation
    myInteger = 2;
  }
  System.out.println("myInteger = " + myInteger);

  switch (a)
  {
    case 1:
      {                    // OK
        System.out.println("Case 1");
        break;
      }
    case 2:
      System.out.println("Case 2");     // OK
      break;
  }
}
        

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

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

Properties

Examples

To configure the check:

<module name="EmptyBlock"/>
        

Example:

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

    try { // violation

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

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:

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

    // violation on next line
    try {

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

To configure the check for default in switch block:

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

Example:

public class Test {
  private void test(int a) {
    switch (a) {
      case 1: someMethod();
      default: // OK, as there is no block
    }
    switch (a) {
      case 1: someMethod();
      default: {} // violation
    }
  }
}
        

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. Pattern "^$" 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. Pattern ".*" 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"/>
        
class Test
{ // Violation - '{' should be on the previous line
  private interface TestInterface
  { // Violation - '{' should be on the previous line
  }

  private
  class
  MyClass { // OK
  }

  enum Colors {RED, // OK
    BLUE,
    GREEN;
  }
}
        

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>
        
class Test
{ // OK
  private interface TestInterface
  { // OK
  }

  private
  class
  MyClass { // Violation - '{' should be on a new line
  }

  enum Colors {RED, // OK
    BLUE,
    GREEN;
  }
}
        

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

<module name="LeftCurly">
  <property name="ignoreEnums" value="false"/>
</module>
        
class Test
{ // Violation - '{' should be on the previous line
  private interface TestInterface
  { // Violation - '{' should be on the previous line
  }

  private
  class
  MyClass { // OK
  }

  enum Colors {RED, // Violation - '{' should have line break after
  BLUE,
  GREEN;
  }
}
        

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 of arrays, lambdas and class instances please follow issue #5945. For right curly brace of enum constant please follow issue #7519.

Properties

name description type default value since
option Specify the policy on placement of a right curly brace ('}'). RightCurlyOption 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 , INTERFACE_DEF , RECORD_DEF , COMPACT_CTOR_DEF . LITERAL_TRY , LITERAL_CATCH , LITERAL_FINALLY , LITERAL_IF , LITERAL_ELSE . 3.0

Examples

To configure the check:

<module name="RightCurly"/>
        

Example:

public class Test {

  public void test() {

    if (foo) {
      bar();
    }           // violation, right curly must be in the same line as the 'else' keyword
    else {
      bar();
    }

    if (foo) {
      bar();
    } else {     // OK
      bar();
    }

    if (foo) { bar(); } int i = 0;  // violation
                  // ^^^ statement is not allowed on same line after curly right brace

    if (foo) { bar(); }            // OK
    int i = 0;

    try {
      bar();
    }           // violation, rightCurly must be in the same line as 'catch' keyword
    catch (Exception e) {
      bar();
    }

    try {
      bar();
    } catch (Exception e) { // OK
      bar();
    }

  }                         // OK

  public void testSingleLine() { bar(); } // OK, because singleline is allowed
}
        

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:

public class Test {

  public void test() {

    if (foo) {
      bar();
    } else { bar(); }   // violation, right curly must be alone on line

    if (foo) {
      bar();
    } else {
      bar();
    }                   // OK

    try {
      bar();
    } catch (Exception e) { // OK because config is set to token METHOD_DEF and LITERAL_ELSE
      bar();
    }

  }                         // OK

  public void violate() { bar; } // violation, singleline is not allowed here

  public void ok() {
    bar();
  }                              // OK
}
        

To configure the check with policy alone_or_singleline for if and METHOD_DEF tokens:

<module name="RightCurly">
  <property name="option" value="alone_or_singleline"/>
  <property name="tokens" value="LITERAL_IF, METHOD_DEF"/>
</module>
        

Example:

public class Test {

  public void test() {

    if (foo) {
      bar();
    } else {        // violation, right curly must be alone on line
      bar();
    }

    if (foo) {
      bar();
    }               // OK
    else {
      bar();
    }

    try {
      bar();
    } catch (Exception e) {        // OK because config did not set token LITERAL_TRY
      bar();
    }

  }                                // OK

  public void violate() { bar(); } // OK , because singleline
}
        

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