Skip to content

Commit 4975fda

Browse files
committed
enhance CatchThrowable rule to improve pattern matching checks and add corresponding tests
1 parent d861b8c commit 4975fda

File tree

2 files changed

+12
-8
lines changed

2 files changed

+12
-8
lines changed

analyzer/src/main/scala/com/avsystem/commons/analyzer/CatchThrowable.scala

+7-8
Original file line numberDiff line numberDiff line change
@@ -22,18 +22,17 @@ class CatchThrowable(g: Global) extends AnalyzerRule(g, "catchThrowable", Level.
2222
case _ => false
2323
}
2424

25+
private def checkTree(pat: Tree): Unit = if (pat.tpe != null && pat.tpe =:= throwableTpe && !isNonFatalPattern(pat)) {
26+
report(pat.pos, "Catching Throwable is discouraged, catch specific exceptions instead")
27+
}
28+
2529
def analyze(unit: CompilationUnit): Unit =
2630
unit.body.foreach {
2731
case t: Try =>
2832
t.catches.foreach {
29-
case cas@CaseDef(Alternative(trees), _, _) =>
30-
if (trees.exists(_.tpe =:= throwableTpe)) {
31-
report(cas.pos, "Catching Throwable is discouraged, catch specific exceptions instead")
32-
}
33-
case cas@CaseDef(pat, _, _) =>
34-
if (pat.tpe != null && pat.tpe =:= throwableTpe && !isNonFatalPattern(pat)) {
35-
report(cas.pos, "Catching Throwable is discouraged, catch specific exceptions instead")
36-
}
33+
case CaseDef(Alternative(trees), _, _) => trees.foreach(checkTree)
34+
case CaseDef(Bind(_, Alternative(trees)), _, _) => trees.foreach(checkTree)
35+
case CaseDef(pat, _, _) => checkTree(pat)
3736
}
3837
case _ =>
3938
}

analyzer/src/test/scala/com/avsystem/commons/analyzer/CatchThrowableTest.scala

+5
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,11 @@ class CatchThrowableTest extends AnyFunSuite with AnalyzerTest {
101101
| } catch {
102102
| case _: IndexOutOfBoundsException | _: NullPointerException => println("OK!")
103103
| }
104+
| try {
105+
| println("test")
106+
| } catch {
107+
| case e@(_: IndexOutOfBoundsException | _: NullPointerException) => println("OK!")
108+
| }
104109
| }
105110
|}
106111
""".stripMargin)

0 commit comments

Comments
 (0)