我正在学习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")或者表达式必须是块表达式?
发布于 2020-08-24 18:02:53
好的。
import scala.util.control.NonFatal
def fourtyseven: PartialFunction[Throwable, Int] = {
case NonFatal(_) => 47
}
def attempt(n: => Int): Int =
try n catch fourtyseven finally println("done")
println(attempt(42))
println(attempt(sys.error("welp")))尽管我必须单独定义catch表达式(因为它需要大括号),但它可以按预期编译和运行。
您可以尝试使用此代码here on Scastie。
以下是几点注意事项:
try/catch/finally是一个返回值的表达式(如果你来自Java语言,这可能会有点陌生) --你可以了解更多关于它的内容,here on the docscatch总是将PartialFunction从Throwable转换为某种类型,try/catch的总体返回类型是这两个类型中最接近的公共超类(例如,假设你有class Animal; class Dog extends Animal; class Cat extends Animal,如果try返回一个Dog,而catch返回一个Cat,则整个表达式将返回一个在catch partial函数中使用NonFatal提取器的catch,您可以在this answer中阅读有关它的更多信息,而提取器对象一般在this answer中描述发布于 2020-08-24 18:42:06
Scala3 (Dotty)正在试验optional braces (显著缩进),因此下面的代码可以工作
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中那样的大括号。实际上,由于在catch关键字之后使用special treatment of case clauses,下面的代码也可以使用
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")https://stackoverflow.com/questions/63558249
复制相似问题