【发布时间】:2011-09-19 21:29:35
【问题描述】:
我在 Python 2.6 上有一个包含与此类似的部分的脚本:
import sys
list_id='cow'
prev=[0,'cow']
try:
if list_id==prev[1]:
print '{0} is the same as {1}'.format(list_id,prev[1])
sys.exit(0)
except:
print 'exception occurred, exiting with error'
sys.exit(1)
我注意到虽然它正在打印“相同”行,但它也记录了异常!
如果您删除 try/except 块,解释器不会显示错误。如果你捕捉到一个特定的错误,比如 ValueError,则不会执行 except 块。
import sys
list_id='cow'
prev=[0,'cow']
try:
if list_id==prev[1]:
print '{0} is the same as {1}'.format(list_id,prev[1])
sys.exit(0)
except Exception as k:
print 'exception occurred, exiting with error. Exception is:'
print k.args
sys.exit(1)
except 块没有被执行,进程以返回码 0 结束。那么,异常在层次结构中的 Exception 之上?
import sys
list_id='cow'
prev=[0,'cow']
try:
if list_id==prev[1]:
print '{0} is the same as {1}'.format(list_id,prev[1])
sys.exit(0)
except BaseException as k:
print 'exception occurred, exiting with error. Exception is:'
print k.args
sys.exit(1)
生产
cow 与发生cow 异常相同,错误退出。
例外是:(0,)
该过程以退出代码 1 结束。
为什么会执行这个 except 块?
【问题讨论】:
-
在这种情况下打印 repr(k) 或 type(k) 比 k.args 提供更多信息。
-
谢谢@Russell,这肯定会有所帮助。
标签: python exception python-2.6