Question about exception-handling mechanism

Fredrik Lundh effbot at telia.com
Tue Apr 25 16:06:21 CEST 2000


willfg at my-deja.com wrote:
>    I'm new to Python, but find its exception handling mechanism much
> more powerful than comparable languages; but a question was put to me
> that being new I can't come up with a very articulate answer. A
> colleague asked why in an exception handling mechanism you'd want the
> ELSE block to be executed if you don't throw an exception as opposed to
> a FINALLY block. Anyone used this feature in practice? Thanks in
> advance for your input.

the standard pattern for try/except/else is:

    try:
        do something
    except SomeError:
        deal with error
    else:
        deal with success
    proceed

this could also be written:

    try:
        do something
        deal with success
    except SomeError:
        deal with error
    proceed

but this only works if the "deal with success"
code cannot raise a SomeError exception...

...

try-finally is different; the code in the finally
clause will be executed in either case, but if
there was an exception, it's reraised after the
finally clause has finished:

    create a mess
    try:
        raise SomeError
    finally:
        clean up
    this line will never be reached

hope this helps!

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->







More information about the Python-list mailing list