Class ExceptionThrowShouldUseContextCheck
java.lang.Object
com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
com.puppycrawl.tools.checkstyle.api.AbstractCheck
com.puppycrawl.tools.checkstyle.checks.coding.ExceptionThrowShouldUseContextCheck
- All Implemented Interfaces:
Configurable,Contextualizable
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.
- Since:
- 14.4.0
-
Nested Class Summary
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
AbstractAutomaticBean.OutputStreamOptions -
Field Summary
Fields -
Constructor Summary
ConstructorsConstructorDescriptionCreates a newExceptionThrowShouldUseContextCheckinstance. -
Method Summary
Modifier and TypeMethodDescriptionprivate static voidaddRecordComponents(DetailAST recordComponents, Set<String> contextVars) Adds record component names to context variables.private static voidcollectCatchVariablesWithContext(DetailAST catchAst, Set<String> contextVars, String catchParamName) Collects variables declared within the catch block whose initializers reference an already identified context variable.private static voidcollectCompactCtorParameters(DetailAST compactCtorDef, Set<String> contextVars) Collects parameters from a compact constructor in a record.collectContextVariables(DetailAST catchAst, String catchParamName) Collects all available context variables in scope: parameters, local variables outside the catch block, applicable enclosing class fields, and variables initialized with context inside the catch block.private static voidcollectFields(DetailAST classDef, Set<String> contextVars, boolean isStaticMethod) Collects field names from an enclosing type's object block, filtering out instance fields when within a static scope.private static voidcollectLocalVariablesOutsideCatch(DetailAST node, DetailAST catchAst, Set<String> contextVars) Recursively collects local variables within a method, skipping the catch AST node and nested types.private static voidcollectParameters(DetailAST methodAst, Set<String> contextVars) Collects parameters from a method, constructor, or lambda.private static voidcollectStandardParameters(DetailAST methodAst, Set<String> contextVars) Collects parameters from a standard method, constructor, or lambda.private static voidcollectThrowStatements(DetailAST node, List<DetailAST> result) Recursively collects all throw statements in a block, skipping nested catches, classes, records, interfaces, and lambdas.private static booleancontainsAnyVariable(DetailAST node, Set<String> variables, String excludedName) Checks if an AST node contains any identifier from the variable set, excluding a given name.private static DetailASTFinds the nearest enclosing class, record, interface, or enum.Finds all enclosing method-like scopes (methods, constructors, or lambdas).int[]The configurable token set.int[]Returns the default token a check is interested in.int[]The tokens that this check must be registered for.private static booleanisInnerClass(DetailAST classDef) Checks if an enclosing class is a non-static inner class.private static booleanisStaticScope(Iterable<DetailAST> methodScopes) Checks if any of the enclosing method scopes is declared static.private static booleanisThrowWithoutContext(DetailAST throwAst, String catchParamName, DetailAST catchAst) Checks if a throw statement throws a new exception without using context variables.private static voidprocessLocalVariableDef(DetailAST child, Set<String> contextVars) Processes a child node and adds any defined local variable name to context variables.voidvisitToken(DetailAST ast) Called to process a token.Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
beginTree, clearViolations, destroy, finishTree, getFileContents, getFilePath, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, leaveToken, log, log, log, setFileContents, setTabWidth, setTokensMethods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
finishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverityMethods inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
configure, contextualize, getConfiguration, setupChild
-
Field Details
-
MSG_KEY
A key is pointing to the warning message text in "messages.properties" file.- See Also:
-
-
Constructor Details
-
ExceptionThrowShouldUseContextCheck
public ExceptionThrowShouldUseContextCheck()Creates a newExceptionThrowShouldUseContextCheckinstance.
-
-
Method Details
-
getDefaultTokens
Description copied from class:AbstractCheckReturns the default token a check is interested in. Only used if the configuration for a check does not define the tokens.- Specified by:
getDefaultTokensin classAbstractCheck- Returns:
- the default tokens
- See Also:
-
getAcceptableTokens
Description copied from class:AbstractCheckThe configurable token set. Used to protect Checks against malicious users who specify an unacceptable token set in the configuration file. The default implementation returns the check's default tokens.- Specified by:
getAcceptableTokensin classAbstractCheck- Returns:
- the token set this check is designed for.
- See Also:
-
getRequiredTokens
Description copied from class:AbstractCheckThe tokens that this check must be registered for.- Specified by:
getRequiredTokensin classAbstractCheck- Returns:
- the token set this must be registered for.
- See Also:
-
visitToken
Description copied from class:AbstractCheckCalled to process a token.- Overrides:
visitTokenin classAbstractCheck- Parameters:
ast- the token to process
-
isThrowWithoutContext
private static boolean isThrowWithoutContext(DetailAST throwAst, String catchParamName, DetailAST catchAst) Checks if a throw statement throws a new exception without using context variables.- Parameters:
throwAst- throw statement astcatchParamName- name of the catch parametercatchAst- enclosing catch ast- Returns:
- true if the throw statement throws a new exception without using context variables
-
collectThrowStatements
Recursively collects all throw statements in a block, skipping nested catches, classes, records, interfaces, and lambdas.- Parameters:
node- AST node to searchresult- list to collect throw statements into
-
containsAnyVariable
private static boolean containsAnyVariable(DetailAST node, Set<String> variables, String excludedName) Checks if an AST node contains any identifier from the variable set, excluding a given name.- Parameters:
node- AST node to searchvariables- set of variable namesexcludedName- identifier name to exclude- Returns:
- true if any variable is found
-
collectContextVariables
Collects all available context variables in scope: parameters, local variables outside the catch block, applicable enclosing class fields, and variables initialized with context inside the catch block.- Parameters:
catchAst- catch AST nodecatchParamName- catch parameter name- Returns:
- set of available context variable names
-
findEnclosingMethodScopes
Finds all enclosing method-like scopes (methods, constructors, or lambdas).- Parameters:
node- starting AST node- Returns:
- list of enclosing method-like AST nodes
-
isStaticScope
Checks if any of the enclosing method scopes is declared static.- Parameters:
methodScopes- method-like scopes- Returns:
- true if any enclosing scope is static
-
collectParameters
Collects parameters from a method, constructor, or lambda.- Parameters:
methodAst- method-like AST nodecontextVars- set to add parameter names to
-
collectCompactCtorParameters
Collects parameters from a compact constructor in a record.- Parameters:
compactCtorDef- compact constructor AST nodecontextVars- set to add parameter names to
-
addRecordComponents
Adds record component names to context variables.- Parameters:
recordComponents- record components AST nodecontextVars- set to add component names to
-
collectStandardParameters
Collects parameters from a standard method, constructor, or lambda.- Parameters:
methodAst- method-like AST nodecontextVars- set to add parameter names to
-
collectLocalVariablesOutsideCatch
private static void collectLocalVariablesOutsideCatch(DetailAST node, DetailAST catchAst, Set<String> contextVars) Recursively collects local variables within a method, skipping the catch AST node and nested types.- Parameters:
node- AST node to searchcatchAst- catch AST node to skipcontextVars- set to add variable names to
-
collectCatchVariablesWithContext
private static void collectCatchVariablesWithContext(DetailAST catchAst, Set<String> contextVars, String catchParamName) Collects variables declared within the catch block whose initializers reference an already identified context variable.- Parameters:
catchAst- catch AST nodecontextVars- set of known context variablescatchParamName- catch parameter name
-
processLocalVariableDef
Processes a child node and adds any defined local variable name to context variables.- Parameters:
child- AST node to inspectcontextVars- set to add variable names to
-
isInnerClass
Checks if an enclosing class is a non-static inner class.- Parameters:
classDef- class AST node- Returns:
- true if the class is a non-static inner class
-
findEnclosingClassLike
Finds the nearest enclosing class, record, interface, or enum.- Parameters:
node- starting AST node- Returns:
- enclosing type AST node, or null if none
-
collectFields
private static void collectFields(DetailAST classDef, Set<String> contextVars, boolean isStaticMethod) Collects field names from an enclosing type's object block, filtering out instance fields when within a static scope.- Parameters:
classDef- enclosing type AST nodecontextVars- set to add field names toisStaticMethod- true if enclosing method is static
-