我试图搜索,但我找不到任何东西。但是我可能只是没有说对。在我正在阅读的书中。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
Run Code Online (Sandbox Code Playgroud)
我的问题是 IOError 之后的 exp 是什么。它有什么作用,为什么会在那里?
它为except块内的异常提供了一个变量名:
>>> try:
... raise Exception('foo')
... except Exception, ex:
... print ex
... print type(ex)
...
foo
<type 'exceptions.Exception'>
Run Code Online (Sandbox Code Playgroud)
我个人觉得as语法更清晰:
>>> try:
... raise Exception('foo')
... except Exception as ex:
... print ex
... print type(ex)
...
foo
<type 'exceptions.Exception'>
Run Code Online (Sandbox Code Playgroud)
但是根据这个问题中的答案,直到 2.6 才引入 as 语法。
| 归档时间: |
|
| 查看次数: |
512 次 |
| 最近记录: |