Skip to content

Commit 5ef14bc

Browse files
committed
Add guarded-fallible-action-within-try.ql
Note that this uses future CodeQL API (`VarWrite`) which is not yet available in the CodeQL library version currently used to build the queries.
1 parent 8a1749a commit 5ef14bc

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* Finds `try` statements which directly contain an `if` statement which guards the actual code which
3+
* can throw the exception the `try` is supposed to catch.
4+
* For example:
5+
* ```java
6+
* try {
7+
* if (condition) {
8+
* doFallibleAction()
9+
* }
10+
* } catch (Exception e) {
11+
* ...
12+
* }
13+
* ```
14+
*
15+
* It might increase readibility to move the `if` statement outside the `try`:
16+
* ```java
17+
* if (condition) {
18+
* try {
19+
* doFallibleAction()
20+
* } catch (Exception e) {
21+
* ...
22+
* }
23+
* }
24+
* ```
25+
*
26+
* @kind problem
27+
* @id todo
28+
*/
29+
30+
// Note: This is a more general (and less precise) variant of `recommendations/resource-used-conditionally.ql`
31+
import java
32+
33+
class ExprWithSideEffects extends Expr {
34+
ExprWithSideEffects() {
35+
this instanceof VarWrite or
36+
this instanceof Call
37+
}
38+
}
39+
40+
from TryStmt tryStmt, IfStmt ifStmt
41+
where
42+
tryStmt.getBlock().(SingletonBlock).getStmt() = ifStmt and
43+
// Ignore if there is a `finally` block which should always run, regardless of condition
44+
not exists(tryStmt.getFinally()) and
45+
not ifStmt.getCondition().getAChildExpr*() instanceof ExprWithSideEffects and
46+
// Ignore if condition uses resource created by `try` statement
47+
not ifStmt.getCondition().getAChildExpr*() =
48+
tryStmt.getAResourceDecl().getAVariable().getAnAccess() and
49+
// Ignore if there is an `else` block (which might also be fallible)
50+
not exists(ifStmt.getElse())
51+
select ifStmt, "Should be moved outside $@", tryStmt, "enclosing try statement"

0 commit comments

Comments
 (0)