try-except syntax

Rob Gaddi rgaddi at highlandtechnology.invalid
Thu Apr 5 17:34:15 EDT 2018


On 04/05/2018 02:04 PM, ElChino wrote:
> 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.

     try:
       _x, pathname, _y = imp.find_module (mod, mod_path)
       return ("%s" % pathname)
     except (ImportError, RuntimeError):
       pass
       return ("<unknown>")

That handles the identical case.  C-style fall-throughs where you have 
one switch have just a bit of code before the fall-through kicks in (the 
slightly non-identical case) is often the source of disastrous code errors.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.



More information about the Python-list mailing list