在try / catch块中最终“超出范围”

时间:2012-02-28 13:44:52

标签: scala try-catch-finally

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

1 个答案:

答案 0 :(得分:12)

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

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