【问题标题】:How to continue processing if an exception is thrown in call to function?如果在函数调用中抛出异常,如何继续处理?
【发布时间】:2014-02-28 08:13:57
【问题描述】:

该函数统计List中指定位置的单词个数,并输出一个Map,其中包含该单词以及该单词在List中被提及的次数:

  def getTopLinks(data: List[String], positionOfElementToCount: Int) = {

    val words = data.map(d => d.split(",")(positionOfElementToCount).trim)
    val wordCount: Map[String, Int] = words.foldLeft(Map.empty[String, Int]) { (m, x) => m + ((x,    m.getOrElse(x, 0) + 1)) }
    val sortedWordCount = wordCount.toList.sortBy { _._2 }.reverse

    sortedWordCount

  }

此方法抛出 java.lang.ArrayIndexOutOfBoundsException 。但是我怎么能在上面的函数中忽略这个异常。如果 List 中的元素引发异常,则忽略它并继续。我认为我不能在行 val words = data.map(d => d.split(",")(positionOfElementToCount).trim) 周围包装一个 try catch,因为这样我就无法继续处理,因为在某处抛出异常在此声明中。

如果这个过程发生在一个 for 循环中,那么我可以在有问题的行周围包裹一个 try catch 并继续,但我认为在这种情况下我不能这样做?

【问题讨论】:

    标签: scala


    【解决方案1】:

    应该使用这个:

    val words = data.flatMap { d =>
          val split = d.split(",")
          if (split.isDefinedAt(positionOfElementToCount))
            Some(split(positionOfElementToCount))
          else None
        }
    

    更简单的完整版本(包括更简洁的@serejja 代码)将是:

    def getTopLinks(data: List[String], positionOfElementToCount: Int) = {
        val words = data.flatMap { d => d.split(",").drop(positionOfElementToCount).headOption }
        words.view.groupBy(x => x).map(x => (x._1 -> x._2.size)).toList
    }   
    

    【讨论】:

      【解决方案2】:

      试试这个:

      val words = data.map(d => d.split(",").drop(positionOfElementToCount).headOption)
      

      这会返回您所需索引上元素的选项,如果索引大于数组大小,则不会引发异常

      【讨论】:

        【解决方案3】:

        试试这个:

        val words = data.flatMap(d => d.split(",").slice(index, index+1).headOption)
        

        【讨论】:

        • 您能解释一下您的解决方案吗?
        • 你只需要从给定位置获取 1 个元素
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-13
        • 1970-01-01
        • 2010-09-13
        • 1970-01-01
        相关资源
        最近更新 更多