前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python try/except/finally

python try/except/finally

作者头像
marsggbo
发布2018-01-23 15:57:21
5070
发布2018-01-23 15:57:21
举报

稍微总结一下,否则总是忘。

x = 'abc' 
def fetcher(obj, index):  
 return obj[index]  
 
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不仅捕获异常,而且会恢复执行

def catcher():  
 try:  
        fetcher(x, 4)  
 except:  
 print "got exception" 
 print "continuing" 

  1. 输出:

got exception  
continuing  

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

def catcher():  
 try:  
        fetcher(x, 4)  
 finally:  
 print 'after fecth' 

输出:

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

def catcher():  
 try:  
        fetcher(x, 4)  
 except:  
 print "got exception" 
 else:  
 print "not exception" 

输出:

got exception  

def catcher():  
 try:  
        fetcher(x, 2)  
 except:  
 print "got exception" 
 else:  
 print "not exception" 

输出:

not exception  

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

第四:利用raise传递异常

def catcher():  
 try:  
        fetcher(x, 4)  
 except:  
 print "got exception" 
 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语句不包括异常名称或额外资料时,会重新引发当前异常。如果希望捕获处理一个异常,而又不希望

异常在程序代码中消失,可以通过raise重新引发该异常。

第五:except(name1, name2)

def catcher():  
 try:  
        fetcher(x, 4)  
 except(TypeError, IndexError):  
 print "got exception" 
 else:  
 print "not exception" 

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

def catcher():  
 try:  
        fetcher(x, 4)  
 except:  
 print "got exception" 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-03-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档