for / while else doesn't make sense

Chris Angelico rosuav at gmail.com
Thu May 19 16:01:23 EDT 2016


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.

ChrisA



More information about the Python-list mailing list