Python 尝试...除了逗号与“as”;除了
except 语句中的 ',' 和 'as' 有什么区别,例如:
try:
pass
except Exception, exception:
pass
and:
try:
pass
except Exception as exception:
pass
第二种语法在 2.6 中合法吗?它可以在 Windows 上的 CPython 2.6 中运行,但 cygwin 中的 2.5 解释器抱怨它无效。
如果它们在 2.6 中都有效,我应该使用哪一个?
What is the difference between ',' and 'as' in except statements, eg:
try:
pass
except Exception, exception:
pass
and:
try:
pass
except Exception as exception:
pass
Is the second syntax legal in 2.6? It works in CPython 2.6 on Windows but the 2.5 interpreter in cygwin complains that it is invalid.
If they are both valid in 2.6 which should I use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最终文档是 PEP-3110:捕获异常
摘要:
as
是必需将异常分配给变量。as
语法,因为它的歧义性要小得多,并且与 Python 3.x 向前兼容。as
。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.是的,这是合法的。我正在运行 Python 2.6
更新:使用
as
语法还有另一个原因。正如其他人指出的那样,使用,
会使事情变得更加模糊;这就是区别所在。从 Python 2.6 开始,有multicatch
允许您 在一个except
块中捕获多个异常。在这种情况下,说出来比说
哪个仍然有效更具有表现力和Python风格
Yes it's legal. I'm running Python 2.6
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 ismulticatch
which allows you to catch multiple exceptions in oneexcept
block. In such a situation, it's more expressive and pythonic to sayrather than to say
which would still work
“as”语法是未来的首选语法,但是如果您的代码需要使用较旧的 Python 版本(2.6 是第一个支持新版本的版本),那么您需要使用逗号语法。
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.
如果你想支持所有Python版本,你可以使用
sys.exc_info()
函数,如下所示:(source:http://python3porting.com/noconv.html)
If you want to support all python versions you can use the
sys.exc_info()
function like this:(source:http://python3porting.com/noconv.html)
从 Python 3.7 开始(不确定其他版本),不再支持“逗号”语法:
源文件
exception_comma.py
:$ python --version --> Python 2.7.10
$ python3 --version --> Python 3.7.2
As of Python 3.7 (not sure about other versions) the 'comma' syntax is not supported any more:
Source file
exception_comma.py
:$ python --version --> Python 2.7.10
$ python3 --version --> Python 3.7.2