python如何处理异常

http://blog.csdn.net/lishan9133/article/details/7023397

利用python捕获异常的方式

方法一:捕获所有的异常

1 ''' 捕获异常的第一种方式,捕获所有的异常 '''
2   try:
3     a = b
4     b = c
5   except Exception,data:
6     print Exception,":",data
7   '''输出:<type 'exceptions.Exception'> : local variable 'b' referenced before assignment ''

方法二:采用traceback模块查看异常,需要导入traceback模块

 1   ''' 捕获异常的第二种方式,使用traceback查看异常 '''
 2 try:
 3     a = b
 4     b = c
 5 except:
 6     print traceback.print_exc()
 7 '''输出: Traceback (most recent call last):
 8 File "test.py", line 20, in main
 9 a = b
10 UnboundLocalError: local variable 'b' referenced before assignmen

方法三:采用sys模块回溯最后的异常

 1 ''' 捕获异常的第三种方式,使用sys模块捕获异常 '''
 2 try:
 3     a = b
 4     b = c
 5 except:
 6     info = sys.exc_info()
 7     print info
 8     print info[0]
 9     print info[1]
10 '''输出:
11 (<type 'exceptions.UnboundLocalError'>, UnboundLocalError("local 
12 variable 'b' referenced before assignment",),
13 <traceback object at 0x00D243F0>)
14 <type 'exceptions.UnboundLocalError'>
15 local variable 'b' referenced before assignment
16 '''
原文地址:https://www.cnblogs.com/lvxiuquan/p/2668806.html