blue-sky
blue-sky

Reputation: 53806

How to continue processing if an exception is thrown in call to function?

This function counts the number of words in a List at a specified position and outputs a Map which contains the word and the number of times this word is mentioned in the 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

  }

This method throws a java.lang.ArrayIndexOutOfBoundsException . But how can I ignore this exception in above function. If the exception is thrown for an element in the List then just ignore it and continue. I don't think I can wrap a try catch around line val words = data.map(d => d.split(",")(positionOfElementToCount).trim) because then I cannot continue to process as the exception is thrown somewhere in this statement.

If this process occured in a for loop then I could just wrap a try catch around the offending line and continue, but i don't think I can do this in this case ?

Upvotes: 0

Views: 236

Answers (3)

Iurii Perevertailo
Iurii Perevertailo

Reputation: 2707

Try this:

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

Upvotes: 1

Jatin
Jatin

Reputation: 31724

Should work with this:

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

A simpler complete version (including @serejja code which is more concise) would be:

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
}   

Upvotes: 1

serejja
serejja

Reputation: 23851

Try this:

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

That returns you an option of the element on the desired index and no exception will be thrown if the index is greater than the array size

Upvotes: 3

Related Questions