ExceptionThrowShouldUseContext
Since Checkstyle 14.4.0
Description
Checks that exception throw statements in catch blocks use context variables.
Rationale: When catching an exception and throwing a new exception, it is recommended to include contextual information in the new exception constructor (such as method parameters, local variables declared outside the catch block, or fields). Failing to include context makes troubleshooting and debugging production issues significantly harder.
Examples
To configure the check:
<module name="Checker">
<module name="TreeWalker">
<module name="ExceptionThrowShouldUseContext"/>
</module>
</module>
Example of violations
class Example1 {
void method1(String someParameter) {
try {
riskyOperation();
}
catch (IOException ex1) {
// violation below 'Exception throw should always use context variables.'
throw new IllegalStateException("unable to process ", ex1);
}
catch (Exception ex2) {
// ok, uses 'someParameter' in the exception constructor
throw new IllegalStateException("unable to process " + someParameter, ex2);
}
}
private void riskyOperation() throws IOException {
}
}
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.
Fully Qualified Name
com.puppycrawl.tools.checkstyle.checks.coding.ExceptionThrowShouldUseContextCheck
Use this fully qualified class name in configuration when an exact class reference is required.






