python异常
捕获异常写法
1 try: 2 print(num) #NameError 3 open("xxx.txt") #FileNotFoundError 4 except A_Exception: 5 xxx 6 except B_Exception: 7 xxx 8 except (C_Exception, D_Exception): #用元组的形式同时捕获多个异常 9 xxx 10 except Exception as e: #Exception是所有异常的父类 11 print(e) #打印捕获到的异常 12 else: #未捕获到异常 13 print("没有捕获到异常") 14 finally: 15 print("无论是否产生异常都执行")
抛出自定义异常
1 class ShortInputException(Exception): 2 '''自定义的异常类''' 3 def __init__(self, length, atleast): 4 #super().__init__() 5 self.length = length 6 self.atleast = atleast 7 8 def main(): 9 try: 10 s = input('请输入 --> ') 11 if len(s) < 3: 12 # raise引发一个你定义的异常 13 raise ShortInputException(len(s), 3) 14 except ShortInputException as result:#x这个变量被绑定到了错误的实例 15 print('ShortInputException: 输入的长度是 %d,长度至少应是 %d'% (result.length, result.atleast)) 16 else: 17 print('没有异常发生.') 18 19 main()