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
?
Scala finally block is used to execute important code such as closing connection, stream or releasing resources( it can be file, network connection, database connection etc). It will be always executed not matter if an exception is thrown or not.
You can only have one finally clause per try/catch/finally statement, but you can have multiple such statements, either in the same method or in multiple methods. Basically, a try/catch/finally statement is: try.
The Try type represents a computation that may either result in an exception, or return a successfully computed value. It's similar to, but semantically different from the scala. util. Either type. Instances of Try[T] , are either an instance of scala.
Just squirrel the Try
away temporarily:
def doWork = {
getLock()
val t = Try(useResource)
releaseLock()
t.get
}
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