IllegalCatch
Since Checkstyle 3.2
Description
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:
class Example1 {
void exampleMethod1() {
try {
// some code here
} catch (Exception e) {
// violation above, 'Catching 'Exception' is not allowed'
}
}
void exampleMethod2() {
try {
// some code here
} catch (ArithmeticException e) {
} catch (Exception e) {
// violation above, 'Catching 'Exception' is not allowed'
}
}
void exampleMethod3() {
try {
// some code here
} catch (NullPointerException e) {
} catch (OutOfMemoryError e) {
}
}
void exampleMethod4() {
try {
// some code here
} catch (ArithmeticException | NullPointerException e) {
}
}
void exampleMethod5() {
try {
// some code here
} catch (OutOfMemoryError e) {
}
}
}
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:
class Example2 {
void exampleMethod1() {
try {
// some code here
} catch (Exception e) {
}
}
void exampleMethod2() {
try {
// some code here
} catch (ArithmeticException e) {
// violation above, 'Catching 'ArithmeticException' is not allowed'
} catch(Exception e){
}
}
void exampleMethod3() {
try {
// some code here
} catch (NullPointerException e) {
} catch (OutOfMemoryError e) {
// violation above, 'Catching 'OutOfMemoryError' is not allowed'
}
}
void exampleMethod4() {
try {
// some code here
} catch (ArithmeticException | NullPointerException e) {
// violation above, 'Catching 'ArithmeticException' is not allowed'
}
}
void exampleMethod5(){
try {
// some code here
} catch (OutOfMemoryError e) {
// violation above, 'Catching 'OutOfMemoryError' is not allowed'
}
}
}
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






