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(_) =>
}
}
}
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.
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.
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.
Yes, it is not mandatory to use catch block with finally.
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(_) =>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With