What's the use of the else in try/except/else?

kj socyl at 987jk.com.invalid
Mon May 11 11:19:05 EDT 2009


In <w_adnY5Q3JzyxJrXnZ2dnUVZ_u2dnZ2d at pdx.net> Scott David Daniels <Scott.Daniels at Acm.Org> writes:

>kj wrote:
>> ...  I can't come with an example in which the same couldn't be
>> accomplished with
>> 
>> try:
>>     # do something
>>     # do something else
>> except ...:
>>     # handle exception
>> 
>> The only significant difference I can come up with is that in the
>> second form, the except clause may be masking some unexpected
>> exceptions from the "do something else" part.  Is this the rationale
>> behind this else clause?  Or is there something more to it?

>Yes, in a way.  The idea of catching particular exceptions is to only
>handle exceptions you expect (let the others go out to more general
>reporters).  So, not only should you choose the tightest exception to
>catch that you can, but you should look for it in a very narrow window:
>exactly where you expect it.

>     try:
>         v = mumble.field
>     except AttributeError:
>         pass
>     else:
>         sys.warning('field was actually there?')

>as opposed to:

>     try:
>         v = mumble.field
>         sys.warning('field was actually there?')
>     except AttributeError:
>         pass

>The idea is to make it clear what you expect might go
>wrong that you are prepared to handle.

Wow.  As rationales for syntax constructs go, this has got to be
the most subtle one I've ever seen...

Thanks!

kynn

-- 
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.



More information about the Python-list mailing list