try..except with empty exceptions

Ian Foote ian at feete.org
Sat Apr 11 10:20:13 EDT 2015


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 11/04/15 08:11, Steven D'Aprano wrote:
> But with try...except, an empty exception list means to catch
> *everything*, not nothing:
> 
> try: ... except a,b,c: # catches a, b, c
> 
> try: ... except a,b: # catches a, b

This example is incorrect. In python3 it is a SyntaxError:

    Python 3.4.0 (default, Apr 11 2014, 13:05:11)
    [GCC 4.8.2] on linux
    Type "help", "copyright", "credits" or "license" for more
    information.
    >>> try:
    ...  1/0
    ... except ValueError, ZeroDivisionError:
      File "<stdin>", line 3
        except ValueError, ZeroDivisionError:
                         ^
    SyntaxError: invalid syntax

In python2 it aliases ValueError as ZeroDivisionError:

    Python 2.7.6 (default, Mar 22 2014, 22:59:56)
    [GCC 4.8.2] on linux2
    Type "help", "copyright", "credits" or "license" for more
    information.
    >>> try:
    ...  1/0
    ... except ValueError, ZeroDivisionError:
    ...  pass
    ...
    Traceback (most recent call last):
      File "<stdin>", line 2, in <module>
    ZeroDivisionError: integer division or modulo by zero

To get the behaviour you expect, you must use parentheses:

    >>> try:
    ...  1/0
    ... except (ValueError, ZeroDivisionError):
    ...  pass
    ...

Regards,
Ian F
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1

iQEcBAEBAgAGBQJVKS2dAAoJEODsV4MF7PWznkAH/jidWhoJ//gsvBr0ByOOOEgc
A+k8HqrkALfzrh3aEjJB3sq19oLfLcepQeFVUh77mJKOMCQdEeyJtqIz6tLc4RUa
L/nXytHygXVTb5HIARGVkPD26gqAleSb9eZUfPeSEvRHy9UbFS7SMmOdkApheDX3
Vq8TOa8EchaYd+S89y9eepZAhGC7n2TNwrNgp36sbHoz/hYUxFNnugP0ow9FM0Wk
MGKGh04c3Lao+6w7a0scz4YKKb8wTdYkyYwlJhEdg3q74+PwYJpkjcGucna745AZ
XlAKlDCJ9LhPgMufuGdRNskJa4TF709ec5hG9itHu1lFKrjH1iJCEU9ntX6hInU=
=zi4K
-----END PGP SIGNATURE-----



More information about the Python-list mailing list