一、错误与异常处理
错误:
1.语法错误print( 2.逻辑错误1/0
异常:
程序出现错误时发出的信号(异常追踪 错误的位置 异常类 异常值)
异常处理就是防止程序崩溃(当然if条件也可以进行异常处理,但是代码可读性不高,代码块乱)
1 # try: 2 # age = input("----->") 3 # int(age) 4 # except ValueError as e: 5 # print(e) 6 # except KeyError as e: 7 # print(e) 8 # except IndexError as e: 9 # print(e)
万能异常
1 # try: 2 # age = input("----->") 3 # int(age) 4 # except Exception as e: 5 # print(e)
异常的其它机构
1 # s1 = ‘hello‘ 2 # try: 3 # int(s1) 4 # except IndexError as e: 5 # print(e) 6 # else: 7 # print(‘try内没有异常执行我‘) 8 # finally: 9 # print(‘无论异常与否,都会执行该模块,通常是进行清理工作‘)
主动触发异常
1 # try: 2 # raise TypeError(‘类型错误‘) 3 # except Exception as e: 4 # print(e)
自定义异常
1 class MyException(BaseException): 2 def __init__(self, msg): 3 self.msg = msg 4 5 6 # raise MyException(‘自己定制的异常‘) 7 print(MyException(‘自己定制的异常‘))
原文地址:https://www.cnblogs.com/Alexephor/p/11219099.html
时间: 2024-10-29 02:24:19