Skip to content

Commit 5d8f132

Browse files
authored
Merge pull request #1509 from felixmulder/topic/better-try-catch-messages
Better `try` and `catch` messages
2 parents 70a8426 + d1eeb5f commit 5d8f132

File tree

3 files changed

+26
-2
lines changed

3 files changed

+26
-2
lines changed

src/dotty/tools/dotc/parsing/Parsers.scala

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1009,9 +1009,23 @@ object Parsers {
10091009
in.nextToken()
10101010
expr()
10111011
} else EmptyTree
1012+
1013+
handler match {
1014+
case Block(Nil, EmptyTree) => syntaxError(
1015+
"`catch` block does not contain a valid expression, try adding a case like - `case e: Exception =>` to the block",
1016+
handler.pos
1017+
)
1018+
case _ =>
1019+
}
1020+
10121021
val finalizer =
1013-
if (handler.isEmpty || in.token == FINALLY) { accept(FINALLY); expr() }
1014-
else EmptyTree
1022+
if (in.token == FINALLY) { accept(FINALLY); expr() }
1023+
else {
1024+
if (handler.isEmpty)
1025+
warning("A try without `catch` or `finally` is equivalent to putting its body in a block; no exceptions are handled.")
1026+
1027+
EmptyTree
1028+
}
10151029
ParsedTry(body, handler, finalizer)
10161030
}
10171031
case THROW =>

tests/neg/emptyCatch.scala

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
object Test {
2+
try {} catch {} // error: `catch` block does not contain a valid expression, try adding a case like - `case e: Exception =>` to the block
3+
}

tests/pos/tryWithoutHandler.scala

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
object Test {
2+
def main(args: Array[String]): Unit = {
3+
try {
4+
println("hello")
5+
}
6+
}
7+
}

0 commit comments

Comments
 (0)