The definitive document is PEP-3110: Catching Exceptions
Summary:
as
is required to assign an exception to a variable.as
syntax, since it is far less ambiguous and forward compatible with Python 3.x.as
isn't supported.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
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With