异常处理


#异常处理:是错误发生的信号,一旦程序出错,就会产生一个异常,应用程序未处理该异常,异常便会抛出,程序随之终止。
#常见异常类型:
#1.语法错误
#2.逻辑错误 IndexError
#3.不存在的类,报:AttributeError
class foo:
    pass
foo.x

#4.不存在的key,报KeyError
k={'a':1}
k['y']

#5.如果0做除数,报ZeroDivisionError

#6.不可迭代类型,报TypeError
for i in 3:
    pass

#7.不能把字符串转化数字,报ValueError
age=input('>>:')
age=int(age)  #int转化为数字

#处理异常try
#格式
try:       #检测下面异常
    出错的代码
except 异常的类型: #捕捉上面的代码的异常类型,相同执行pass
  pass

try:
    l=[]
    print(l[1])
    print('11111')
except IndexError:
    pass

#as e 拿到异常的值#异常分三部分,异常的追踪信息,异常的类,异常的值。
try:
    l=[]
    print(l[1])
    print('11111')
except IndexError as e:
    print('index',e)

#多个except异常捕捉
try:
    l = []
    print(l[1])
    print('11111')
    d={}
    d=['x']
except IndexError as e:
    print('index',e)
except KeyError as e:
    print('key',e)

#Exception匹配所有异常
try:
    l = []
    print(l[1])
    print('11111')
    d={}
    d=['x']
except Exception as e:
    print('excrption',e)

#例:
try:
    l = []
    print(l[1])
    print('11111')
    d={}
    d=['x']
except IndexError as e:
    print('index',e)
except KeyError as e:
    print('key',e)
except Exception as e:
    print('excrption',e)

#except与else 连用,else:没有异常发生的时候触发。
try:
    l = []
    print(l[1])
    print('11111')
    d={}
    d=['x']
except IndexError as e:
    print('index',e)
except KeyError as e:
    print('key',e)
except Exception as e:
    print('excrption',e)
else:
    print('没有异常')

#finally #有没有异常都触发,应用场景回收系统资源。
try:
    l = []
    print(l[1])
    print('11111')
    d={}
    d=['x']
except IndexError as e:
    print('index',e)
except KeyError as e:
    print('key',e)
except Exception as e:
    print('excrption',e)
else:
    print('没有异常')
finally:
    print('有没有异常都触发')

#raise #主动抛出异常
stu=['sdf','er']
if len(stu) == 0:
    raise  TypeError
print('raise')

#assert #断言(同上)
stu=['sdf','er']
assert len(stu) > 0
print('assert')

#自定义异常
class My(BaseException):
    def __init__(self,msg):
        super(My,self).__init__()  #父类重用
        self.msg=msg

    def __str__(self): #内置函数,打印时触发,默认打印内存地址
        return '<%s> %self.msg'
raise  My('类型错误') #异常的值,print(obj)