2012-02-28 30 views
7

有没有方法可以访问finally块中的try/catch块中创建的val?或者是最终阻止了范围。在try/catch块中终于“超出范围”

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

你不这样做,最后只能看到东西宣告了try/catch语句范围,而不是内部的它。 – 2012-02-28 13:47:34

回答

12

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

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

谢谢,这工作得很好。当然,我不需要'终于'在这里。 Java仍然在我的脑海中。 – 2012-02-28 14:55:27

+1

事实上,你的事件不需要匹配;)只需按照try和catch子句中的值进行操作,然后“返回”它们即可) – tuxSlayer 2012-02-28 20:44:37

+0

如果Java仍在你的脑海中,你必须知道范围规则..catch..finally在Java中是一样的。 – 2012-03-04 01:39:01