IllegalCatch

Since Checkstyle 3.2

Description

Checks that certain exception types do not appear in a catch statement.

Rationale: catching java.lang.Exception, java.lang.Error or java.lang.RuntimeException is almost never acceptable. Novice developers often simply catch Exception in an attempt to handle multiple exception classes. This unfortunately leads to code that inadvertently catches NullPointerException, OutOfMemoryError, etc.

Properties

name description type default value since
illegalClassNames Specify exception class names to reject. String[] Error, Exception, RuntimeException, Throwable, java.lang.Error, java.lang.Exception, java.lang.RuntimeException, java.lang.Throwable 3.2

Examples

To configure the check:

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

Example:

try {
    // some code here
} catch (Exception e) { // violation

}

try {
    // some code here
} catch (ArithmeticException e) { // OK

} catch (Exception e) { // violation, catching Exception is illegal
                          and order of catch blocks doesn't matter
}

try {
    // some code here
} catch (ArithmeticException | Exception e) { // violation, catching Exception is illegal

}

try {
    // some code here
} catch (ArithmeticException e) { // OK

}
        

To configure the check to override the default list with ArithmeticException and OutOfMemoryError:

<module name="Checker">
  <module name="TreeWalker">
    <module name="IllegalCatch">
      <property name="illegalClassNames" value="ArithmeticException,
                  OutOfMemoryError"/>
    </module>
  </module>
</module>
        

Example:

try {
    // some code here
} catch (OutOfMemoryError e) { // violation

}

try {
    // some code here
} catch (ArithmeticException e) { // violation

}

try {
    // some code here
} catch (NullPointerException e) { // OK

} catch (OutOfMemoryError e) { // violation

}

try {
    // some code here
} catch (ArithmeticException | Exception e) {  // violation

}

try {
    // some code here
} catch (Exception e) { // OK

}
        

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