【问题标题】:Surround failing higher order function with try catch?用try catch包围失败的高阶函数?
【发布时间】:2013-08-31 07:41:24
【问题描述】:

以下代码抛出异常:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at line
(s(0).toString,s(0).toString)

我想捕获这个异常,然后将 map 函数继续到下一个项目。如何在高阶函数周围使用 try / catch 以忽略任何异常并继续执行其余函数:groupBy 和 mapValues ?

println(toIterate.toList.map(s => (s(0).toString,s(0).toString))
    .groupBy(_._1)
    .mapValues(_.map(_._2)))

【问题讨论】:

    标签: scala


    【解决方案1】:

    您可以在 Try 中执行 String 索引。 Try 将返回 Success 或 Failure,如下例所示。然后,您可以匹配这些值以组成表达式的其余部分。我会把它留给你作为练习。

    scala> val f = "foo"
    f: String = foo
    
    scala> List(0,1,2,3,4).map(xs => Try(f(xs)))
    res0: List[scala.util.Try[Char]] = List(Success(f), Success(o), Success(o), Failure(java.lang.StringIndexOutOfBoundsException: String index out of range: 3), Failure(java.lang.StringIndexOutOfBoundsException: String index out of range: 4))
    

    【讨论】:

      【解决方案2】:

      如果您的目标是过滤掉会发生异常的项目,您应该使用filter:

      println(toIterate.toList
          .filter(_.length > 0)
          .map(s => (s(0).toString,s(0).toString))
          .groupBy(_._1)
          .mapValues(_.map(_._2)))
      

      【讨论】:

      • 我的主要目标是允许执行继续,即使在任何字符串元素上引发 IndexOutOfBounds 异常
      • 这完成了同样的事情,但是通过识别会发生异常的情况并跳过它。
      【解决方案3】:

      如果您的问题是关于 try 和 catch 的语法,谷歌搜索“try catch scala”会显示一些选项。但我认为更现实的答案是在模式映射时使用“if”条件(参考这篇优秀的文章)以及“Collect”

      http://danielwestheide.com/blog/2012/12/12/the-neophytes-guide-to-scala-part-4-pattern-matching-anonymous-functions.html#comment-975636567

      类似这样的东西(对不起,您可能不得不使用语法)

      println(toIterate.toList.collect(case(s) if s.len>0).map( s => (s(0).toString,s(0).toString)) .groupBy(_._1) .mapValues(_.map(_._2)))
      

      【讨论】:

        猜你喜欢
        • 2017-05-01
        • 2021-11-02
        • 2011-07-19
        • 2012-03-29
        • 2021-01-26
        • 2010-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多