7

Is there a way to access val's created in a try/catch block within the finally block ? or is the finally block out of scope.

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(_) =>
    }
  }
}
Dan Burton
  • 53,238
  • 27
  • 117
  • 198
Peter Lerche
  • 469
  • 4
  • 6

1 Answers1

12

Why do you need to do this in the finally block? Since a try/catch is an expression, you can match on its value:

try {
  val w = runOrFailWithException("Please work...")
  Right(w)
} catch {
  case ex: Exception => Left(ex)
} match {
  case Right(_) =>
  case Left(_) =>
}
Ben James
  • 121,135
  • 26
  • 193
  • 155
  • Thank you, this is working very well. Of course, I don't need `finally` here. - Java is still somewhere in the back of my head. – Peter Lerche Feb 28 '12 at 14:55
  • 1
    Actually you event don't need a match ;) just do what you want with values inside try and catch clauses and then "return" them ) – tuxSlayer Feb 28 '12 at 20:44
  • If Java's still in the back of your head you must know that the scope rules for try..catch..finally are the same in Java. – Ricky Clarkson Mar 04 '12 at 01:39