码迷,mamicode.com
首页 > 其他好文 > 详细

异常处理

时间:2017-11-28 21:06:13      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:coding   class   name   print   sch   blog   key   处理   com   

在python脚本运行过程中如果出现什么问题,会报错,还会停止脚本的运行。我们可以用异常处理来解决这种问题

#-*- coding:utf-8 -*-
__author__ = "MuT6 Sch01aR"

name = [‘test‘,‘alex‘]

try:
    name[3]
#except Exception   抓取全部的错误
#except (KeyError,IndexError)  抓取部分的错误
except KeyError as e:
    print (‘没有这个key‘,e)
except IndexError as e:
    print (‘列表错误‘,e)
except Exception as e:
    print (‘未知错误‘,e)
else:
    print (‘一切正常‘)
finally:
    print (‘不管有没有错都执行‘)

 运行结果

技术分享图片

和没有进行异常处理的运行结果进行比较

技术分享图片

脚本运行时要是出错,爆出出错的原因

异常处理

标签:coding   class   name   print   sch   blog   key   处理   com   

原文地址:http://www.cnblogs.com/sch01ar/p/7911973.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!