Skip to main content
 首页 » 编程设计

Python try...except 逗号 vs 'as' in except

2025年05月04日15grandyang

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

try: 
    pass 
except Exception, exception: 
    pass 

和:

try: 
    pass 
except Exception as exception: 
    pass 

第二种语法在 2.6 中合法吗?它适用于 Windows 上的 CPython 2.6,但 cygwin 中的 2.5 解释器提示它无效。

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

请您参考如下方法:

权威文件是PEP-3110: Catching Exceptions

总结:

  • 在 Python 3.x 中,需要使用 as 将异常分配给变量。
  • 在 Python 2.6+ 中,使用 as 语法,因为它的歧义少得多并且与 Python 3.x 向前兼容。
  • 在 Python 2.5 及更早版本中,使用逗号版本,因为不支持 as。