def doWork() = {
getLock()
Try(useResource) match {
case Success(result) => releaseLock(); result
case Failure(e: Exception) => releaseLock(); throw e
}
}
I'm trying to idiomatically make sure a lock is released when I exit doWork
. However as part of that method I may throw an exception, so I can't just release the lock at the end of doWork
.
It looks like a bit of code smell to have releaseLock()
repeated twice. I could cut that down by using the traditional Java-style try/catch/finally:
def doWork() = {
getLock()
try {
useResource
} catch {
case e: Exception => throw e
} finally {
releaseLock()
}
}
But I prefer to use Scala's Try
if possible.
Is there a way to perform "finally" logic from within the framework of Try
?