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. '''

相关文章
相关标签/搜索