Python try…except comma vs 'as' in except

前端 未结 5 970
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 15:14

What is the difference between \',\' and \'as\' in except statements, eg:

try:
    pass
except Exception, exception:
    pass

and:

相关标签:
5条回答
  • 2020-11-22 15:44

    If you want to support all python versions you can use the sys.exc_info() function like this:

    try:
        a = 1/'0'
    except (ZeroDivisionError, TypeError):
        e = sys.exc_info()[1]
        print(e.args[0])
    

    (source:http://python3porting.com/noconv.html)

    0 讨论(0)
  • 2020-11-22 15:45

    the "as" syntax is the preferred one going forward, however if your code needs to work with older Python versions (2.6 is the first to support the new one) then you'll need to use the comma syntax.

    0 讨论(0)
  • 2020-11-22 15:53

    As of Python 3.7 (not sure about other versions) the 'comma' syntax is not supported any more:

    Source file exception_comma.py:

    try:
        result = 1/0
    except Exception, e:
        print("An error occurred")
        exit(1)
    
    exit(0)
    
    • $ python --version --> Python 2.7.10
    $ python exception_comma.py
    An error occurred
    
    • $ python3 --version --> Python 3.7.2
    $ python3 exception_comma.py
      File "exception_comma.py", line 3
        except Exception, e:
                        ^
    SyntaxError: invalid syntax
    
    0 讨论(0)
  • 2020-11-22 15:54

    Yes it's legal. I'm running Python 2.6

    try:
        [] + 3
    except Exception as x:
        print "woo hoo"
    
    >>> 
    woo hoo
    

    Update: There is another reason to use the as syntax. Using , makes things a lot more ambiguous, as others have pointed out; and here's what makes the difference. As of Python 2.6, there is multicatch which allows you to catch multiple exceptions in one except block. In such a situation, it's more expressive and pythonic to say

    except (exception1, exception2) as e
    

    rather than to say

    except (exception1, exception2), e
    

    which would still work

    0 讨论(0)
  • 2020-11-22 15:56

    The definitive document is PEP-3110: Catching Exceptions

    Summary:

    • In Python 3.x, using as is required to assign an exception to a variable.
    • In Python 2.6+, use the as syntax, since it is far less ambiguous and forward compatible with Python 3.x.
    • In Python 2.5 and earlier, use the comma version, since as isn't supported.
    0 讨论(0)
提交回复
热议问题