python学习DAY10(异常)

参考:https://www.cnblogs.com/wupeiqi/articles/5017742.html
names =['li','lack']
data={}
#异常:
#name[3]
#data['name']
#***
Error
#***

异常处理:
try:
    names[3]
    data['name']
except Exception as item:        #此句意是出现错误后用item接收这个错误信息方便下面打印输出
    print("出错了",e)             #程序从上到下执行,捕捉到第一个异常就不执行后面的代码了

#---小结(一般不常用)
try:
    code
except (Error1,Error2) as item:  #多个已知错误
    print(item)
except Exception as item:        #一般放在最后面,抓住所有(未知)错误
    print(item)
    

else:
    print("一切正常")
    

finally:
    print("无论对错都执行")
#---


#自定义异常
class MyException(Exception):
 
    def __init__(self, msg):
        self.message = msg
 
    def __str__(self):
        return self.message        #下面item输出的内容便是message的内容 
try:
    raise MyException('我的异常')  #raise触发异常
except MyException,item:
    print item
原文地址:https://www.cnblogs.com/god-for-speed/p/11362790.html