Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"return" and "try-catch-finally" block evaluation in scala

Tags:

scala

The following two code generate different result:

def x = try{
  true
} finally false

invoke x gets true

def y:Boolean = try{
  return true
} finally {
  return false
}

invoke y gets false

the return version behave same as Java.

Personally I never use 'return' in scala. But it's good to know how scala evaluate the value of a try-catch-finally block. Thanks.

like image 445
xiefei Avatar asked Dec 09 '11 09:12

xiefei


People also ask

Can we use return statement in try catch or finally block?

Yes, we can write a return statement of the method in catch and finally block.

What is the difference between try catch vs try finally constructs?

The catch block is only executed if an exception is thrown in the try block. The finally block is executed always after the try(-catch) block, if an exception is thrown or not.

What is the difference between a try catch block and a try catch finally block?

The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error.


2 Answers

You should not have a return statement in a finally block (even though it is technically allowed, at least in Java, C# for example forbids it).

If the Scala finally block had an implicit return, that would always clobber the intended return value. So that makes no sense.

But I suppose it cannot help you if you explicitly write it that way.

like image 192
Thilo Avatar answered Oct 07 '22 07:10

Thilo


According to the Scala language spec:

A try expression try { b } finally e evaluates the block b. If evaluation of b does not cause an exception to be thrown, the expression e is evaluated. If an exception is thrown during evaluation of e, the evaluation of the try expression is aborted with the thrown exception. If no exception is thrown during evaluation of e, the result of b is returned as the result of the try expression.

This behaviour would seem to be in contradiction with that spec. I would guess that, since 'return' causes an immediate return from the function, this results in overriding the standard behaviour for a try block. An illuminating example is:

def z : Boolean = {
  val foo = try { true } finally { return false }
  true
}

Invoking z returns false.

like image 29
Submonoid Avatar answered Oct 07 '22 06:10

Submonoid