加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

从Scala中的异常返回的正确方法是什么?

发布时间:2020-12-16 19:18:00 所属栏目:安全 来源:网络整理
导读:在非功能性语言中,我可能会这样做: try { // some stuff} catch Exception ex { return false;}// Do more stuffreturn true; 然而,在Scala中,这种模式显然不正确.如果我的scala代码如下所示: try { // do some stuff}catch { case e: Exception = // I wa
在非功能性语言中,我可能会这样做:

try {
  // some stuff
} catch Exception ex {
  return false;
}

// Do more stuff

return true;

然而,在Scala中,这种模式显然不正确.如果我的scala代码如下所示:

try {
  // do some stuff
}
catch {
  case e: Exception => // I want to get out of here and return false
  )
}

// do more stuff

true

我该怎么做呢?当然,我不想使用“return”语句,但我也不想通过“做更多的事情”并最终返回true.

解决方法

您希望表示可以成功或发出错误信号的计算.这是Try monad的完美用例.

import scala.util.{ Try,Success,Failure }

def myMethod: Try[Something] = Try {
  // do stuff
  // do more stuff
  // if any exception occurs here,it gets wrapped into a Failure(e)
}

因此,你将返回一个Try而不是Bool,它更加清晰和惯用.

用法示例:

myMethod match {
  case Success(x) => println(s"computation succeded with result $x")
  case Failure(e) => println(s"computation failed with exception $e.getMessage")  
}

如果您甚至不关心异常,但只想在成功的情况下返回值,您甚至可以将Try转换为选项.

def myMethod: Option[Something] = Try {
  // do stuff
  // do more stuff
  // return something
  // if any exception occurs here,it gets wrapped into a Failure(e)
}.toOption

myMethod match {
  case Some(x) => println(s"computation succeded with result $x")
  case None => println("computation failed")  
}

要回复评论中的问题,您可以这样做

Try {
  // do stuff
} match {
   case Failure(_) => false
   case Success(_) =>
     // do more stuff
     // true
}

虽然我建议返回比布尔值更有意义的东西,只要它有意义.

当然这可以嵌套

Try {
  // do stuff
} match {
   case Failure(_) => false
   case Success(_) =>
     // do more stuff
     Try {
       // something that can throw
     } match {
       case Failure(_) => false
       case Success(_) =>
         // do more stuff
         true
     }
}

但你应该考虑把Try块放到不同的函数中(返回一个Try).

最终,我们可以利用Try是monad的事实,并做这样的事情

Try { /* java code */ }.flatMap { _ =>
  // do more stuff
  Try { /* java code */ }.flatMap { _ =>
    // do more stuff
    Try { /* java code */ }
  }
} match {
  case Failure(_) => false // in case any of the Try blocks has thrown an Exception 
  case Success(_) => true // everything went smooth
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读