Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

analogous Try block to try/finally block in scala

What is the analogous in manners of scala Try to:

timer.start()
try {
  doThis()
} finally {
  timer.cancel()
}
like image 374
Jas Avatar asked Jun 03 '14 05:06

Jas


People also ask

Can we use try with finally block in the same code?

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.

What is a try finally 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.

Does finally {} block always run?

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.


2 Answers

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.

like image 179
Régis Jean-Gilles Avatar answered Nov 08 '22 11:11

Régis Jean-Gilles


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.

like image 22
Norbert Radyk Avatar answered Nov 08 '22 12:11

Norbert Radyk