for / while else doesn't make sense

Ian Kelly ian.g.kelly at gmail.com
Thu May 19 16:11:42 EDT 2016


On Thu, May 19, 2016 at 2:01 PM, Chris Angelico <rosuav at gmail.com> wrote:
> On Fri, May 20, 2016 at 3:46 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>> The idea of finally is
>> that it executes no matter what happens[1].
>>
>> [1] Well, *almost* no matter what. If you pull the power from the computer,
>> the finally block never gets a chance to run.
>
> Nor if you kill -9 the process, or get into an infinite loop, or any
> number of other things. Specifically, what the finally block
> guarantees is that it will be executed *before any code following the
> try block*. In this example:
>
> try:
>     code1
> except Exception:
>     code2
> else:
>     code3
> finally:
>     code4
> code5
>
> Once you hit code1, you are absolutely guaranteed that code5 *will
> not* be run prior to code4.

The guarantee is stronger than that. It's possible to exit the try
block without passing execution to code5 at all. The finally block is
still guaranteed to be executed in this case.



More information about the Python-list mailing list