Since Checkstyle 3.2
Restricts nested try-catch-finally blocks to a specified depth.
| name | description | type | default value | since |
|---|---|---|---|---|
| max | Specify maximum allowed nesting depth. | int | 1 |
3.2 |
To configure the check:
<module name="Checker">
<module name="TreeWalker">
<module name="NestedTryDepth"/>
</module>
</module>
case 1: Example of code with violation:
try {
try {
try { // violation, current depth is 2, default max allowed depth is 1
} catch (Exception e) {
}
} catch (Exception e) {
}
} catch (Exception e) {
}
case 1: Example of compliant code:
try {
try { // OK, current depth is 1, default max allowed depth is also 1
} catch (Exception e) {
}
} catch (Exception e) {
}
case 2: Example of code for handling unique and general exceptions
try {
try { // OK, current depth is 1, default max allowed depth is also 1
// any more nesting could cause code violation!
throw ArithmeticException();
} catch (ArithmeticException e) { // catches arithmetic exceptions
} catch (NumberFormatException e) { // catches number-format exceptions
} catch (Exception e) { // catches general exceptions other than stated above
}
} catch (
ArithmeticException
| NumberFormatException
| ArrayIndexOutOfBoundsException e) { // catches any of the 3 exception
} catch (Exception e) { // catches general exception
} finally { // do something when try-catch block finished execution
}
To configure the check to allow nesting depth 3:
<module name="Checker">
<module name="TreeWalker">
<module name="NestedTryDepth">
<property name="max" value="3"/>
</module>
</module>
</module>
Example of code with violation:
try {
try {
try {
try {
try { // violation, current depth is 4, max allowed depth is 3
} catch (Exception e) {
}
} catch (Exception e) {
}
} catch (Exception e) {
}
} catch (Exception e) {
}
} catch (Exception e) {
}
Example of compliant code:
try {
try {
try {
try { // OK, current depth is 3, max allowed depth is also 3
} catch (Exception e) {
}
} catch (Exception e) {
}
} catch (Exception e) {
}
} catch (Exception e) {
}
All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.
com.puppycrawl.tools.checkstyle.checks.coding