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

Scott David Daniels Scott.Daniels at Acm.Org
Sun May 10 18:52:23 EDT 2009


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.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list