[英]Is `finally` block executed in case there is `return` inside a `try` or a `catch` block?
[英]Is finally “out of scope” in a try/catch block
有沒有辦法訪問在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(_) =>
}
}
}
為什么你需要在finally
塊中執行此操作? 由於try/catch
是一個表達式,因此您可以匹配其值:
try {
val w = runOrFailWithException("Please work...")
Right(w)
} catch {
case ex: Exception => Left(ex)
} match {
case Right(_) =>
case Left(_) =>
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.