【问题标题】:Is finally "out of scope" in a try/catch block终于在 try/catch 块中“超出范围”
【发布时间】:2012-02-28 13:44:52
【问题描述】:

有没有办法访问在 finally 块中的 try/catch 块中创建的 val?或者是最终块超出范围。

def myTryCatch: Either[Exception, String] = {
  try {
    val w = runOrFailWithException("Please work...")
    Right(w)
  } catch {
    case ex: Exception => {
      Left(ex)
    }
  }
  finally {
    // How do I get access to Left or Right in my finally block.
    // This does not work
    _ match {
      case Right(_) =>
      case Left(_) =>
    }
  }
}

【问题讨论】:

  • 你没有,最后只能看到声明在 try/catch 范围之外的东西,而不是在它里面。

标签: scala try-catch-finally


【解决方案1】:

为什么需要在finally 块中执行此操作?因为 try/catch 是一个表达式,你可以匹配它的值:

try {
  val w = runOrFailWithException("Please work...")
  Right(w)
} catch {
  case ex: Exception => Left(ex)
} match {
  case Right(_) =>
  case Left(_) =>
}

【讨论】:

  • 谢谢,这很好用。当然,我这里不需要finally。 - Java 仍然在我脑海中的某个地方。
  • 实际上你的事件不需要匹配;) 只需使用 try 和 catch 子句中的值做你想做的事,然后“返回”它们)
  • 如果 Java 还在你的脑海中,你一定知道 try..catch..finally 的作用域规则在 Java 中是一样的。
猜你喜欢
  • 1970-01-01
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-25
  • 2011-02-20
  • 2021-09-10
  • 1970-01-01
相关资源
最近更新 更多