星期一, 四月 02, 2007

python try/except variable scope?

>>> try:
... testr = "still be effective in the except?"
... raise "exception"
... except:
... print testr
...
still be effective in the except?
所以在 try 中定义的变量在 except 中仍有效!

然后看看下面这种情况:
>>> try:
... for item in ['A', 'B', 'C']:
... print item
... raise "exception"
... except:
... print item
...
A
B
C
C
注意这里的 item,在 excpet 中仍然有效,只不过只是最后一个值。

再改成 finally:
>>> try:
... testr = "still be effective in the except?"
... raise "exception"
... finally:
... print testr
...
still be effective in the finally
Traceback (most recent call last):
File "", line 3, in ?
exception

没有评论: