方法一:捕獲所有的異常
1
2
3
4
5
6
7
8
|
''' 捕獲異常的第一種方式,捕獲所有的異常 ''' try : a = b b = c except Exception,data: print Exception, ":" ,data '' '輸出:<type ' exceptions.Exception '> : local variable ' b' referenced before assignment '' |
方法二:採用traceback模塊查看異常,需要導入traceback模塊
1
2
3
4
5
6
7
8
9
10
|
''' 捕獲異常的第二種方式,使用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模塊回溯最後的異常
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
''' 捕獲異常的第三種方式,使用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 ''' |