【问题标题】:Handle exception in for comprehension处理异常以进行理解
【发布时间】:2013-03-20 15:58:26
【问题描述】:

我应该如何处理理解中的潜在异常?在此示例中,我想处理行格式不正确时发生的MatchException。我想抛出一个包含行字符串的信息更丰富的异常。问题是行字符串仅在 inside for 理解中知道,但使用 try/catch 的传统错误处理将在 outside 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.10 的 Try 在这里可能会有所帮助,但我仍在使用 2.9.2。

【问题讨论】:

  • 看起来像 Try was backported to 2.9.3 以及 Futures 和 Promises,因此您可以轻松迁移到 2.9.3(与 2.9.1/2 二进制兼容,只需交换工件)并享受它
  • 酷,我仍然不确定如何准确地使用它来获取行文本。

标签: scala exception


【解决方案1】:

使用匹配运算符似乎更简单

line.split("\t") match {
  case Array(a, s, _ @ _*) => (a, s)
  case _ => throw new MatchError("Line '"+line+"' not in proper form")
}

【讨论】:

    【解决方案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 在这里只是有点帮助;我不会担心的。

    【讨论】:

      【解决方案3】:

      如果按照 om-nom-nom 的建议你得到 Try,你可以做这样的事情

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

      简而言之,您的recover,将异常重新包装成你想要的,然后解包结果或使用get抛出新异常

      如果您无法获取Try,因为try...catch 是Scala 中的表达式而不是语句,您可以使用它编写几乎相同的东西。

      Array( annotation, string, _@ _* ) = 
      try { line.split( "\t" )} catch { case e: Exception =>  throw new MyException("my message")}
      

      【讨论】:

        猜你喜欢
        • 2012-09-01
        • 2013-05-12
        • 1970-01-01
        • 2014-06-15
        • 2015-01-03
        • 2022-07-29
        • 1970-01-01
        • 1970-01-01
        • 2011-08-15
        相关资源
        最近更新 更多