Python try...except 逗号 vs 'as' in except [英] Python try...except comma vs 'as' in except

查看:51
本文介绍了Python try...except 逗号 vs 'as' in except的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

except 语句中的,"和as"有什么区别,例如:

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

try:
    pass
except Exception, exception:
    pass

和:

try:
    pass
except Exception as exception:
    pass

2.6 中的第二种语法是否合法?它适用于 Windows 上的 CPython 2.6,但 cygwin 中的 2.5 解释器抱怨它无效.

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.

如果它们在 2.6 中都有效,我应该使用哪个?

If they are both valid in 2.6 which should I use?

推荐答案

最终文档是 PEP-3110:捕获异常

总结:

  • 在 Python 3.x 中,必须使用 as 为变量分配异常.
  • 在 Python 2.6+ 中,使用 as 语法,因为它没有歧义,并且与 Python 3.x 向前兼容.
  • 在 Python 2.5 及更早版本中,请使用逗号版本,因为不支持 as.
  • 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.

这篇关于Python try...except 逗号 vs 'as' in except的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆