python try/except/finally

在这里插入图片描述

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

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" 

更多Python的学习资料可以扫描下方二维码无偿领取!!!

1)Python所有方向的学习路线(新版)

总结的Python爬虫和数据分析等各个方向应该学习的技术栈。

在这里插入图片描述

比如说爬虫这一块,很多人以为学了xpath和PyQuery等几个解析库之后就精通的python爬虫,其实路还有很长,比如说移动端爬虫和JS逆向等等。

img

(2)Python学习视频

包含了Python入门、爬虫、数据分析和web开发的学习视频,总共100多个,虽然达不到大佬的程度,但是精通python是没有问题的,学完这些之后,你可以按照我上面的学习路线去网上找其他的知识资源进行进阶。

在这里插入图片描述

(3)100多个练手项目

我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了,只是里面的项目比较多,水平也是参差不齐,大家可以挑自己能做的项目去练练。

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值