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:
m1
will return with 1
.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!
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.
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.
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.
Yes, the finally block will be executed even after a return statement in a method.
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.
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