Skip to main content
 首页 » 编程设计

python之except 子句中的逗号

2025年05月04日17Terrylee

我试过搜索,但找不到任何东西。但是我可能只是没有说对。在我正在阅读的书中。 Dave Kuhlman 的 Python 书 他编写了一个 try:except 语句来捕获 IOError。

def test(): 
    infilename = 'nothing.txt' 
    try: 
        infile = open(infilename, 'r') 
        for line in infile: 
            print line 
    except IOError, exp: 
        print 'cannot open file "%s"' % infilename 

我的问题是 IOError 之后的 exp 是什么。它有什么作用,为什么在那里?

请您参考如下方法:

它为 except block 中的异常提供了一个变量名:

>>> try: 
...     raise Exception('foo') 
... except Exception, ex: 
...     print ex 
...     print type(ex) 
... 
foo 
<type 'exceptions.Exception'> 

我个人觉得 as 语法更清晰:

>>> try: 
...     raise Exception('foo') 
... except Exception as ex: 
...     print ex 
...     print type(ex) 
... 
foo 
<type 'exceptions.Exception'> 

但是根据 this question 中的答案,直到 2.6 才引入 as 语法。 .