Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is finally "out of scope" in a try/catch block

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(_) =>
    }
  }
}
like image 680
Peter Lerche Avatar asked Feb 28 '12 13:02

Peter Lerche


People also ask

What is finally block in try catch?

catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed. The code in the finally block will always be executed before control flow exits the entire construct.

Do try catch blocks have scope?

try/catch creates a new scope for the simple reason that it is a block level element. In fact, simply placing {} just randomly inside a method will create a new block of code with it's own local scope.

Can we have try catch finally within a try block?

Core Java bootcamp program with Hands on practiceNo, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.

Can we use a finally block with out a catch?

Yes, it is not mandatory to use catch block with finally.


1 Answers

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(_) =>
}
like image 177
Ben James Avatar answered Sep 29 '22 20:09

Ben James