# 1.异常只能用来处理指定的异常取代,如果非指定异常则无法处理
# 2多分支:被监测的代码块抛出的异常有多种可能性,并且我们需要针对每一种异常类型都定制专门的处理逻辑
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)
print(1)
except IndexError as e:
print('----------->', e)
print(2)
except KeyError as e:
print('----------->', e)
print(3)
print('执行接下去的代码')
'''如果遇到 NameError 执行结果:
========>1
-----------> name 'name' is not defined
####执行完跳到 print('执行接下去的代码')
'''
'''如果遇到 IndexError 执行结果:
========>1
==========>2
-----------> list index out of range
####执行完跳到 print('执行接下去的代码')
'''
'''如果遇到 KeyError 执行结果:
========>1
==========>2
==========>3
-----------> 'name'
####执行完跳到 print('执行接下去的代码')
'''
# 万能异常:Exception ,被监测的代码块抛出的异常有多种可能性,
# 并且我们针对所有的异常类型都只用一种处理逻辑就可以了,那就使用Exception
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('执行接下去的代码')
# 其他结构:
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)
print(1)
except IndexError as e:
print('----------->', e)
print(2)
except KeyError as e:
print('----------->', e)
print(3)
except Exception as e:
print('统一的处理方法',333)
else:
print('在被监测的代码块没有发生异常时执行')
finally:
print('不管被监测的代码块有无发生异常都会执行')
print('执行接下去的代码')
# 主动触发异常:raise 异常类型(值)
class People:
def __init__(self,name,age):
if not isinstance(name,str):
raise TypeError('name传入必需是字符串类型')
if not isinstance(age,int):
raise TypeError('age 传入必需是int类型')
self.name=name
self.age=age
p = People('kingfor',18)
# 自定义异常类型:
class MyException(BaseException):
def __init__(self,msg):
super(MyException,self).__init__()
self.msg = msg
def __str__(self):
return '<%s>' % self.msg
raise MyException('我自定义异常处理类型')
# 断言assert
info = {}
info['name'] = 'kingforn'
info['age'] = 18
# if 'name' not in info:
# raise KeyError('必须有name这个key')
# if 'age' not in info:
# raise KeyError('必须有name这个key')
assert ('name' in info) and ('age' in info)
if info['name'] == 'kingforn' and info['age'] >10:
print('welcome')