[Tutor] How much in a "try" block?

Peter Otten __peter__ at web.de
Fri Aug 23 14:14:35 CEST 2013


Alan Gauld wrote:

> On 22/08/13 21:27, Chris Down wrote:
> 
>> You can also use the "else" clause if there is stuff you want to run if
>> the try block doesn't raise the caught exception, which avoids putting it
>> in "try" if you don't intend to exit from the exception.
> 
> 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.
> 
> I   guess where h() is not using x it might be helpful but in most(all?)
> of my code I've usually bailed when x has gone
> wrong or I've fixed things such that hg() and h() are required.
> 
> I'm curious, how often do others use the try/else combination?

I use it for clarity even when it is not necessary. I think

try:
    text = file.read()
except AttributeError:
    with open(file) as f:
        text =  f.read()

looks odd (an AttributeError when reading a file?) compared to

try:
    read = file.read
except AttributeError:
    with open(file) as f:
        text = f.read()
else:
    text = read()

Ah -- we're not sure whether it's a file or a filename.

Looking through my bunch of casual scripts I find that 22% of try...except 
have an else clause compared to only 11.4% in /usr/lib/python2.7.



More information about the Tutor mailing list