On 23/08/13 10:30, Alan Gauld wrote:

I admit that I've never really found a use for else in a try block.
I don;t see much advantage in

try: f(x)
except MyError:
     pass
else:
     g(x)
h(x)

over

try: f(x)
except MyError:
     pass
g(x)
h(x)

Unless you really only want g(x) executed if there
is no MyError exception but want h(x) executed regardless.


That's exactly the use-case for try...else. Admittedly, it's a relatively 
uncommon use-case, but when you need it, you need it.

Instead of writing something like this:

failed = False
try:
    do_stuff()
except SomeException:
    failed = True
    handle_error()
if not failed:
    do_something_else()
always_do_this()


a cleaner design is to use try...else:

try:
    do_stuff()
except SomeException:
    handle_error()
else:
    do_something_else()
always_do_this()



The advantage of try...else is even more obvious when you combine it with a 
finally clause:


try:
    do_stuff()
except SomeException:
    handle_error()
else:
    do_something_else()
finally:
    cleanup()
always_do_this()


The cleanup function runs no matter how you exit the try block, whether it is 
via the except clause, the else clause, or even an unhandled exception. In this 
case, do_something_else is supposed to run before cleanup. I might be tempted 
to write this instead:


failed = False
try:
    do_stuff()
except SomeException:
    failed = True
    handle_error()
finally:
    cleanup()
if not failed:
    do_something_else()
always_do_this()


but that's wrong, because now do_something_else runs after cleanup. So I would 
have to use two try blocks to match the behaviour of try...else...finally.

try:
    failed = False
    try:
        do_stuff()
    except SomeException:
        failed = True
        handle_error()
    if not failed:
        do_something_else()
finally:
    cleanup()
always_do_this()



I'm curious, how often do others use the try/else combination?

Rarely :-)


In my statistics module[1], out of nearly 2300 lines of code including doc strings, I use 
"else" just ten times in total and none of them are from try...else.

On the other hand, in my startup file that runs when I launch the Python 
interactive interpreter, a mere 157 lines, I have *four* try...else blocks. So 
it really depends on the nature of the code. Here is a typical example:


# === Command line completion and history ===
try:
    import history
except ImportError:
    print('*** warning: command line history not available ***')
else:
    history = history.History()




[1] http://www.python.org/dev/peps/pep-0450/



--
Steven
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to