如果我在内部抛出异常,以下代码如何打印 Success(4) ? [英] How come the following code prints Success(4) if i'm throwing an exception inside?

查看:29
本文介绍了如果我在内部抛出异常,以下代码如何打印 Success(4) ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 应该失败,因为我在那里抛出异常?

How come it printed Success(4) didn't the doOne was supposed to fail as i'm throwing exception there?

推荐答案

将代码包裹在花括号中,例如,

wrap the code inside curly braces like,

def doOne(i: Int): Int = {i + 1; throw new RuntimeException("failed in one")}

throw new RuntimeException("failed in one") 不在函数内,它是主流内的单独一行.

The throw new RuntimeException("failed in one") is not within the function it is a separate line inside main flow.

这篇关于如果我在内部抛出异常,以下代码如何打印 Success(4) ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆