2

内包表記で潜在的な例外を処理するにはどうすればよいですか? MatchExceptionこの例では、行が適切にフォーマットされていないときに発生するa を処理したいと考えています。行の文字列を含む、より有益な例外をスローしたいと思います。問題は、行の文字列がfor 内包でしか認識されていないことですが、従来のエラー処理try/catchはfor 内包で行われます。

    val gold = Resource.using (Source.fromFile(file)) { source =>
      (for {
        line <- source.getLines
        Array(annotation, string, _ @ _*) = line.split("\t")
        boolean = if (annotation == "1") true else false
      } yield {
        string -> boolean
      }).toMap
    }

ここではScala 2.10Tryが役立つかもしれませんが、私はまだ 2.9.2 を使用しています。

4

3 に答える 3

4

一致演算子を使用する方が簡単なようです

line.split("\t") match {
  case Array(a, s, _ @ _*) => (a, s)
  case _ => throw new MatchError("Line '"+line+"' not in proper form")
}
于 2013-03-20T17:10:13.597 に答える
2

例外をより詳細に更新することだけが必要な場合は、次のことができます。

for {
  line <- List("salmon\tcod", "wooble")
  (annotation, string) = try { 
    val Array(a, s, _ @ _*) = line.split("\t"); (a, s)
  } catch {
    case me: MatchError => throw new MatchError("Line '"+line+"' not in proper form")
  }
  boolean = (annotation=="1")
} yield (string -> boolean)

つまり、解析を行い、tryブロック内で必要なものを返します。 Tryここでは少しだけ役に立ちます。私はそれについて心配しません。

于 2013-03-20T16:33:08.563 に答える
1

If as suggested by om-nom-nom you get Try, you can do something like this

Array( annotation, string, _@ _* ) = 
                Try( line.split( "\t" )).recover({ case e: Exception => Failure(new MyException("my message")) }).get 

In short your recover, rewrap the Exception in what you want then unwrap the result or throw the new exception using get

If you cannot get hold of Try since try...catch is an expression in Scala and not a statement, you can write almost the same thing using it.

Array( annotation, string, _@ _* ) = 
try { line.split( "\t" )} catch { case e: Exception =>  throw new MyException("my message")}
于 2013-03-20T16:24:51.323 に答える