object MyRealMainObj extends App {
println(
Try(1)
.map(doOne)
.map(doTwo)
)
def doOne(i: Int): Int = i + 1; throw new RuntimeException("failed in one")
def doTwo(i: Int): Int = i + 2
}
结果:
Success(4)
Exception in thread "main" java.lang.RuntimeException: failed in one
at MyRealMainObj$.delayedEndpoint$MyRealMainObj$1(TestMainArgs.scala:16)
at MyRealMainObj$delayedInit$body.apply(TestMainArgs.scala:7)
at scala.Function0$class.apply$mcV$sp(Function0.scala:40)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App$$anonfun$main$1.apply(App.scala:76)
at scala.App$$anonfun$main$1.apply(App.scala:76)
怎么打印Success(4)
doOne
不应该失败,因为我在那里抛出异常?
答案 0 :(得分:4)
将代码包装在大括号内,如
def doOne(i: Int): Int = {i + 1; throw new RuntimeException("failed in one")}
抛出新的RuntimeException("在一个"中失败)不在函数内,它是主流内的一个单独的行。