zoukankan      html  css  js  c++  java
  • Python try/except/finally

    举例说明一下try/except/finally的用法。

    若不使用try/except/finally

    1 x = 'abc'
    2 def fetcher(obj, index):
    3     return obj[index]
    4 
    5 fetcher(x, 4)

    输出:

      File "test.py", line 6, in <module>
        fetcher(x, 4)
      File "test.py", line 4, in fetcher
        return obj[index]
    IndexError: string index out of range

    使用try/except/finally:

    第一: try不仅捕获异常,而且会恢复执行

    1 def catcher():
    2     try:
    3         fetcher(x, 4)
    4     except:
    5         print "got exception"
    6     print "continuing"

    输出:

    got exception
    continuing

    第二:无论try是否发生异常,finally总会执行

    1 def catcher():
    2     try:
    3         fetcher(x, 4)
    4     finally:
    5         print 'after fecth'

    输出:(这里没用except,即没有在异常发生时的处理办法,就按python默认的方式来对待异常发生,故程序会停下来)

    after fecth
    Traceback (most recent call last):
      File "test.py", line 55, in <module>
        catcher()
      File "test.py", line 12, in catcher
        fetcher(x, 4)
      File "test.py", line 4, in fetcher
        return obj[index]
    IndexError: string index out of range

    第三:try无异常,才会执行else

    有异常的情况

    1 def catcher():
    2     try:
    3         fetcher(x, 4)
    4     except:
    5         print "got exception"
    6     else:
    7         print "not exception"

    输出:

    got exception  

    没异常的情况:

    1 def catcher():
    2     try:
    3         fetcher(x, 2)
    4     except:
    5         print "got exception"
    6     else:
    7         print "not exception"

    输出:

    not exception  

    else作用:没有else语句,当执行完try语句后,无法知道是没有发生异常,还是发生了异常并被处理过了。通过else可以清楚的区分开。

    第四:利用raise传递异常

    1 def catcher():
    2     try:
    3         fetcher(x, 4)
    4     except:
    5         print "got exception"
    6         raise

    输出:

    got exception
    Traceback (most recent call last):
      File "test.py", line 37, in <module>
        catcher()
      File "test.py", line 22, in catcher
        fetcher(x, 4)
      File "test.py", line 4, in fetcher
        return obj[index]
    IndexError: string index out of range

    raise语句不包括异常名称或额外资料时,会重新引发当前异常(即发生了异常才进入except内的异常)。如果希望捕获处理一个异常,而又不希望异常在程序代码中消失,可以通过raise重新引发该异常。

    第五:except(name1, name2)

    1 def catcher():
    2     try:
    3         fetcher(x, 4)
    4     except(TypeError, IndexError):
    5         print "got exception"
    6     else:
    7         print "not exception"

    捕获列表列出的异常,进行处理。若except后无任何参数,则捕获所有异常。

    1 def catcher():
    2     try:
    3         fetcher(x, 4)
    4     except:
    5         print "got exception"
  • 相关阅读:
    用confluence完成室项目管理网站的初步搭建
    初中英语单词词库 for supermemo
    用supermemo背单词4年了
    武汉一点印象
    借个iPad玩玩,越狱4.2.1成功
    TIOBE在2011年3月发布的编程语言排名表
    复杂的工作机构,一把手真是不易
    自己做的项目竟然与马拉松石油公司的数字油田思路惊人的相似!
    iPhone开发笔记[1/50]:初学iPhone上用Quartz 2D画图
    背单词的词条终于达到6500
  • 原文地址:https://www.cnblogs.com/haoshine/p/5777537.html
Copyright © 2011-2022 走看看