What is the analogous in manners of scala Try
to:
timer.start()
try {
doThis()
} finally {
timer.cancel()
}
Answer: Yes, if we have a cleanup code that might throw an exception in the finally block, then we can have a try-catch block.
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
A finally block always executes, regardless of whether an exception is thrown. The following code example uses a try / catch block to catch an ArgumentOutOfRangeException.
Given that an exception inside a Try
simply creates a Failure
value (as opposed to transferring control to an outer catch block when using try
), the code in your original finally
block would just need to be executed after the Try
.
In other words, this will do:
timer.start()
val result = Try{
doThis()
}
timer.cancel()
result
As far as I know there is no built-in shortcut that would allow to avoid capturing result
just to return it as is.
Since Try
won't throw an exception in your program flow I believe just write the following:
timer.start()
Try(doThis())
timer.cancel()
You can assign Try(doThis())
to a value and process it further if you wish to process the exception (rather than blindly ignoring it) or the call result.
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