Python异常处理体系简介
2010-09-22 11:09:22 来源:WEB开发网捕获异常的方式
方法一:捕获所有的异常
''' 捕获异常的第一种方式,捕获所有的异常 '''
try:
a = b
b = c
except Exception,data:
print Exception,":",data
'''输出:<type 'exceptions.Exception'> : local variable 'b'
referenced before assignment ''
方法二:采用traceback模块查看异常,需要导入traceback模块
''' 捕获异常的第二种方式,使用traceback查看异常 '''
try:
a = b
b = c
except:
print traceback.print_exc()
'''输出: Traceback (most recent call last):
File "test.py", line 20, in main
a = b
UnboundLocalError: local variable 'b' referenced before assignmen
方法三:采用sys模块回溯最后的异常
''' 捕获异常的第三种方式,使用sys模块捕获异常 '''
try:
a = b
b = c
except:
info = sys.exc_info()
print info
print info[0]
print info[1]
'''输出:
(<type 'exceptions.UnboundLocalError'>, UnboundLocalError("local
variable 'b' referenced before assignment",),
<traceback object at 0x00D243F0>)
<type 'exceptions.UnboundLocalError'>
local variable 'b' referenced before assignment
'''
更多精彩
赞助商链接