7

有没有办法访问在 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(_) =>
    }
  }
}
4

1 回答 1

12

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

try {
  val w = runOrFailWithException("Please work...")
  Right(w)
} catch {
  case ex: Exception => Left(ex)
} match {
  case Right(_) =>
  case Left(_) =>
}
于 2012-02-28T13:48:17.713 回答