2013-08-30 27 views
0

下面的代碼拋出異常:嘗試捕捉環繞失敗的高階函數?

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

我想趕上這個例外,只是不斷的地圖功能到下一個項目。如何圍繞高階函數圍繞try/catch,以忽略任何異常並繼續其餘函數:groupBy & mapValues?

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

回答

3

你可以做一個TryString索引。 Try將返回SuccessFailure,如下例所示。然後您可以匹配這些值來組成表達式的其餘部分。我會把它作爲你的練習。

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)) 
0

如果你的目標是過濾掉哪裏會出現異常的項目,你應該使用filter

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

我的主要目標是允許繼續執行即使IndexOutOfBounds異常被任意的字符串拋出elemens –

+0

這完成同樣的事情,但通過識別將發生異常情況,並跳過它。 –

0

谷歌搜索「嘗試捕捉階」,就會發現一些選項,如果你的問題是關於try和catch的聯繫。但我認爲,更現實的答案將在模式映射的沿點(參考這個優秀的文章)「如果」條件中使用和「收集」

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)))