python学习,day7 异常处理

# coding=utf-8
# Author: RyAn Bi
names=['alex','jack']
data = {}
try:
    # names[3]
    # data['name']
    #open('text.txt')
    a = 1
    print(a)
# except Exception as e:       #抓住所有的错误,一般不用,因为无法定位错误
#     print('出错了',e)
except (KeyError,IndexError) as e:  #可以多个异常一并处理
   print('没有这个key',e)
except IndexError as e:    #抓住indexerror
   print('列表操作错误',e)
except Exception as e:     #放到最后
    print('未知错误',e)
else:
    print('一切正常')  #没有错误,运行这个
finally:
    print('不管有没有错,都执行')

#缩进错误等等语法错误,无法抓住
# coding=utf-8
# Author: RyAn Bi

class BryanException(Exception): #定义一个异常
    def __init__(self,msg):
        self.message = msg
    # def __str__(self):
    #     return  'abc'

try:
    raise BryanException('数据库连不上')
except BryanException as e:
    print(e)

 

posted @ 2020-07-09 16:54  bbgoal  阅读(94)  评论(0编辑  收藏  举报