首页 > 解决方案 > Scala try-catch-finally 表达式可以没有大括号吗?

问题描述

我正在学习 Scala 并对try-catch-finally语法感到困惑。

Scala Syntax Specification中,它说:

Expr1             ::=  ‘try’ Expr [‘catch’ Expr] [‘finally’ Expr]
                     | ...

我可以写没有{ }这样的块的表达式:

try
  println("Hello")
catch
  RuntimeException e => println("" + e)
finally
  println("World")

或者表达式必须是块表达式?

标签: scala

解决方案


Scala 3 (Dotty) 正在试验可选大括号(显着缩进),因此以下工作

scala> try
     |   1 / 0
     | catch
     |   case e => println(s"good catch $e")
     | finally
     |   println("Celebration dance :)")
     |
good catch java.lang.ArithmeticException: / by zero
Celebration dance :)
val res1: AnyVal = ()

我们注意到处理程序的地方

case e => println(s"good catch $e")

不需要像Scala 2中那样的大括号。事实上,由于关键字后的子句的特殊处理,casecatch以下也可以工作

scala> try
     |   1 / 0
     | catch
     | case e => println(s"good catch $e")
     | finally
     |   println("Celebration dance :)")
     |
good catch java.lang.ArithmeticException: / by zero
Celebration dance :)
val res2: AnyVal = ()

我们注意到处理程序不必在之后缩进catch

catch
case e => println(s"good catch $e")

推荐阅读