python try catch

捕獲異常的方式

 

方法一:捕獲全部的異常

  1. try:
    spa

  2. a = bio

  3. b = cast

  4. except Exception,data:test

  5. print Exception,":",dataobject

  6. '''輸出:<type 'exceptions.Exception'> : local variable 'b'
    exception

  7. referenced before assignment '方法

 

方法二:採用traceback模塊查看異常,須要導入traceback模塊,這個方法會打印出異常代碼的行號

  1. try:
    call

  2. a = b異常

  3. b = cco

  4. except:

  5. print traceback.print_exc()


  6. '''輸出: Traceback (most recent call last):

  7. File "test.py", line 20, in main

  8. a = b

  9. UnboundLocalError: local variable 'b

 

方法三:採用sys模塊回溯最後的異常

  1. try:

  2. a = b

  3. b = c

  4. except:

  5. info = sys.exc_info()

  6. print info

  7. print info[0]

  8. print info[1]


  9. '''輸出:

  10. (<type 'exceptions.UnboundLocalError'>, UnboundLocalError("local

  11. variable 'b' referenced before assignment",),

  12. <traceback object at 0x00D243F0>)

  13. <type 'exceptions.UnboundLocalError'>

  14. local variable 'b' referenced before assignment

  15. '''

相關文章
相關標籤/搜索