Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the semantics of return from block inside ensured blocks?

Tags:

smalltalk

Assume we have the following sequence of methods:

m1
    self m2: [^1]

m2: block
    self m3: block.
    Processor := nil "crash!"

m3: block
    [block value] ensure: [^2]

The question is what's the value of anObject m1?

In other words, is the semantics of [ˆ2] well defined as an ensured block? There are two possibilities:

  1. The return from block is ignored in ensured blocks: In this case m1 will return with 1.
  2. The return from block is honored in ensured blocks: In this case the image will crash.

Please note that I'm not asking what will happen. I'm rather interested in the definition of the execution flow.


EDIT

COROLLARY 1 (as confirmed by Lukas in his answer below): Not a good programming style!

like image 867
Leandro Caniglia Avatar asked Jan 09 '15 01:01

Leandro Caniglia


People also ask

What is the use of the return block?

If you have an error condition, just "return" out of the method. It saves wrapping the rest of your work in an else block. Seems trivial, but it helps to reduce code complexity. The compiler will actually rewrite a method to look like you described.

Can we return in finally block Python?

You'll notice that python always returns the last thing to be returned, regardless that the code "reached" return 1 in both functions. A finally block is always run, so the last thing to be returned in the function is whatever is returned in the finally block.

Will finally block executed if the catch block executed?

A finally block is always get executed whether the exception has occurred or not. If an exception occurs like closing a file or DB connection, then the finally block is used to clean up the code. We cannot say the finally block is always executes because sometimes if any statement like System.

Does the finally block get executed if either of try or catch blocks return the control?

Yes, the finally block will be executed even after a return statement in a method.


1 Answers

Check page 23 of the Draft of ANSI Smalltalk Standard that describes the return statement and its interaction with ensure: blocks:

If the evaluation of a termination block concludes with the execution of a return statement the result is undefined.

like image 79
Lukas Renggli Avatar answered Nov 18 '22 14:11

Lukas Renggli