python -多分支和异常的捕获
2019-03-10 本文已影响0人
wangcc_sd
多分支:被监测的代码块抛出的异常有多种可能性,并且我们需要针对每一种异常类型都定制专门的处理逻辑
try:
print('===>1')
# name
print('===>2')
l=[1,2,3]
# l[100]
print('===>3')
d={}
d['name']
print('===>4')
except NameError as e:
print('--->',e)
except IndexError as e:
print('--->',e)
except KeyError as e:
print('--->',e)
print('====>afer code')
万能异常:Exception
# -*-coding:utf-8 -*-
# BY WANGCC
try:
print('===>1')
# name
print('===>2')
l=[1,2,3]
l[100]
print('===>3')
d={}
d['name']
print('===>4')
except Exception as e:
print('异常发生啦:',e)
print('====>afer code')
raise 异常类型(值)
#主动触发异常:raise 异常类型(值)
# class People:
# def __init__(self,name,age):
# if not isinstance(name,str):
# raise TypeError('名字必须传入str类型')
# if not isinstance(age,int):
# raise TypeError('年龄必须传入int类型')
#
# self.name=name
# self.age=age
#
# p=People('egon',18)