打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
python try/except/finally

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

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

输出:

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

第一: try不仅捕获异常,而且会恢复执行
  1. def catcher():  
  2.     try:  
  3.         fetcher(x, 4)  
  4.     except:  
  5.         print "got exception"  
  6.     print "continuing"  
输出:
  1. got exception  
  2. continuing  

第二:无论try是否发生异常,finally总会执行
  1. def catcher():  
  2.     try:  
  3.         fetcher(x, 4)  
  4.     finally:  
  5.         print 'after fecth'  
输出:
  1. after fecth  
  2. Traceback (most recent call last):  
  3.   File "test.py", line 55, in <module>  
  4.     catcher()  
  5.   File "test.py", line 12, in catcher  
  6.     fetcher(x, 4)  
  7.   File "test.py", line 4, in fetcher  
  8.     return obj[index]  
  9. 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"  
输出:
  1. got exception  
  1. def catcher():  
  2.     try:  
  3.         fetcher(x, 2)  
  4.     except:  
  5.         print "got exception"  
  6.     else:  
  7.         print "not exception"  
输出:
  1. not exception  
else作用:没有else语句,当执行完try语句后,无法知道是没有发生异常,还是发生了异常并被处理过了。通过else可以清楚的区分开。

第四:利用raise传递异常

  1. def catcher():  
  2.     try:  
  3.         fetcher(x, 4)  
  4.     except:  
  5.         print "got exception"  
  6.         raise  
输出:
  1. got exception  
  2. Traceback (most recent call last):  
  3.   File "test.py", line 37, in <module>  
  4.     catcher()  
  5.   File "test.py", line 22, in catcher  
  6.     fetcher(x, 4)  
  7.   File "test.py", line 4, in fetcher  
  8.     return obj[index]  
  9. IndexError: string index out of range  
raise语句不包括异常名称或额外资料时,会重新引发当前异常。如果希望捕获处理一个异常,而又不希望

异常在程序代码中消失,可以通过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"  


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
pylearn2安装及测试
python 一个.py文件如何调用另一个.py文件中的类和函数
simplejson处理不严谨JSON python json Invalid control character
将Python脚本文件包装成可执行文件
让apache支持 mod
Redis的Python客户端redis-py
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服