使用except而带多种异常类型
# num=[1,2,3,4,5]
# try:
# open('qwe.txt','r')
# list[4]
# except (NameError,FileNotFoundError) as rese:
# print('出现异常')
# else:
# print('没有异常')
异常的传递
# def funcl():
# print("-"*20)
# print(num)
# print('-'*20)
# def func3():
# try:
# print("=" * 20)
# funcl()
# print('=' * 20)
# except Exception as result:
# print(result)
# print('='*20)
# func3()
触发异常
可以使用raise自己触发异常
def name( score):
if score< 0 or score>100:
raise Exception('Invalid scorel',score)
name(200)
用户自定义异常
class ShortInputException(Exception):
def __init__(self, length, atleast):
self.length = length
self.atleast = atleast
def main():
try:
s = input('输入任意数据')
if len(s) < 3:
# raise引发一个你定义的异常
raise ShortInputException(len(s), 3)
except ShortInputException as result:#x这个变量被绑定到了错误的实例
print('ShortInputException: 输入的长度是 %d,长度至少应是 %d'% (result.length, result.atleast))
else:
print('没有异常发生')
main()
```