python基础2-异常处理

1、异常处理

names = ['alex','jack']
data = {}

try:
    a = 1
    print(a)
    # names[3]
    # data['name']
    open("test.txt")
except KeyError as e:
    print("没有这个key",e)
except IndexError as e:
    print("列表操作错误",e)

except (IndexError,KeyError) as e:
    print("统一处理办法的时候抛出该错",e)

except Exception as e:
    print("Exception是抓住所有错误,未知错误",e)
    #当然如:缩进,语法等是无法抓取到的

else:
    print("一切正常")

finally:
    print("不管有没有错,都执行")

  

 

2、自定义异常

class LlyException(Exception):
    def __init__(self,msg):
        self.message = msg
    # def __str__(self):
    #     return "LlyException"

try:
    raise LlyException("数据库连接不上")
except LlyException as e:
    print(e)

#返回:数据库连接不上

  

3、断言

class C:
    def __init__(self):
        self.name = 'lly'
obj = C()
print(obj.name)
assert type(obj.name) is str
print("确实是字符串")

#返回:

'''
lly
确实是字符串
'''

  

posted @ 2017-10-03 10:54  larlly  阅读(119)  评论(0)    收藏  举报