try-except syntax

Ben Bacarisse ben.lists at bsb.me.uk
Thu Apr 5 17:51:44 EDT 2018


ElChino <elchino at cnn.cn> writes:

> I'm trying to simplify a try-except construct. E.g. how come
> this:
>   try:
>     _x, pathname, _y = imp.find_module (mod, mod_path)
>     return ("%s" % pathname)
>   except ImportError:
>     pass
>   except RuntimeError:
>     pass
>     return ("<unknown>")
>
> Cannot be simplified into this:
>   try:
>     _x, pathname, _y = imp.find_module (mod, mod_path)
>     return ("%s" % pathname)
>   except ImportError:
>   except RuntimeError:
>     pass
>     return ("<unknown>")
>
> Like a "fall-through" in a C-switch statement.

The except parts don't fall through, and each one needs a "suite".
Also, the "pass" before the return is mysterious which makes me think
there's an indent error in what you posted.

Anyway, to coalesce two or more exception handlers, you are probably
looking for

  except (ImportError, RuntimeError):

which matches both.

-- 
Ben.



More information about the Python-list mailing list