【发布时间】:2017-10-15 08:36:08
【问题描述】:
我正在尝试学习如何在 scala 中使用 Try with 进行推导。
在下面的示例代码中(result1),
如果 for comprehension 中的最后一条语句抛出未处理的异常, 代码不会中断并返回 Try[Int]。
但是,如果为了理解(result2)改变了语句的顺序。抛出运行时异常。
package simpleTryExample
import scala.util.Try
object SimpleTryExample {
def main(args: Array[String]): Unit = {
val result1 = for {
a <- strToInt("3")
b <- strToInt("a")
} yield (a + b)
println("result1 is " + result1)
val result2 = for {
a <- strToInt("a")
b <- strToInt("3")
} yield (a + b)
println("result2 is " + result2)
}
def strToInt(s: String): Try[Int] = {
s match {
case "a" =>
println("input is a")
throw new RuntimeException("a not allowed")
case _ => println("other then a")
}
Try(s.toInt)
}
}
输出:-
other then a
input is a
Exception in thread "main" java.lang.RuntimeException: a not allowed
at simpleTryExample.SimpleTryExample$.strToInt(SimpleTryExample.scala:30)
at simpleTryExample.SimpleTryExample$.main(SimpleTryExample.scala:18)
at simpleTryExample.SimpleTryExample.main(SimpleTryExample.scala)
result1 is Failure(java.lang.RuntimeException: a not allowed)
input is a
我期望 result2 是 Try[Int] 类型。 我在这里做错了什么..?
【问题讨论】:
标签: scala error-handling try-catch for-comprehension