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

Andre Engels andreengels at gmail.com
Thu May 14 03:08:24 EDT 2009

On Thu, May 14, 2009 at 6:39 AM, ma <mabdelkader at gmail.com> wrote:
> A really great use for try/except/else would be if an object is
> implementing its own __getitem__ method, so you would have something
> like this:
> class SomeObj(object):
>    def __getitem__(self, key):
>                try:
>                        #sometype of assertion here based on key type
>                except AssertionError, e:
>                        raise TypeError, e #invalid type
>                else:
>                        #continue processing, etc.. return some index, which will auto throw
>                        #an index error if you have some type of indexable datastructure

Again, this is a case where no else is needed. Whenever you raise
something in the except clause (as your only exit point), it would
work just as well (though it might be a bit uglier) to put the rest
after the try ... except without an else. It is when after the
exception execution continues normally, but skipping part of the code,
that you need an else.

André Engels, andreengels at gmail.com

More information about the Python-list mailing list