ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 异常和错误 --- [TOC] ## 错误类型 |code|错误类型| |---|---| |a NameError |未定义变量| |if True SyntaxError | 语法错误| |f =open('1.txt') | IOError -IO错误| |10/0 |ZeroDivisionError | |a = int('ab') | ValueError| ## 捕获一种错误并打印 try: a except NameError as e: print("catch Error",e) ## 捕获所有错误 try: 10/0 except NameError as e: print("catch Error",e) except Exception as e: print('all error') ## else try: 10/1 except ValueError as e: print("catch Error",e) else: print("success") >若没有错误则打印 success ## try-finally try: f=open("1.txt") print(int(f.read())) finally: print("file close") f.close() >1. 规则: try-finally 无论是否检测到异常,都会执行finally代码 >2. 作用: 为异常处理时间提供清理机制,用来关闭文件或者释放系统资源:如果存在异常,先处理异常,在处理finally ## try-except-else-finally try: f=open("./template/hello1.html") except NameError as e: print("NameError:",e) else: print("no Error") finally: print("file close") f.close() #输出 no Error file close ## with ### with context [as var] >1. with 语句用来代替try-except_final 语句 ,使代码更加简洁 >文件打开推荐使用with ,他可以自动关闭文件 ### with 语句实质是上下文管理 >1. 上下文管理协议:包含__enter__()和__exit__(),支持该协议必须该对象支持此方法 >2. 上下文管理器:定义执行with语句时要简历的运行时上下文,负责执行with语句块上下文中的进入与推出操作 >3. 进入上下文管理器:调用管理器__enter__方法,日过设置 as var 语句 var变量接受__enter__()方法返回值 ## raise 主动抛出异常 >语法格式 raise [exception[,args]] >exception : 异常类 ,如 ValueError,TypeError python 2.x 写法 raise TypeError,"error" python 3.x写法 raise TypeError("errormessage") --- try: raise TypeError("error message") raise Exception("普通错误类型") except TypeError as e: print("TypeError:",e) except Exception as e: print('Exception :'+str(e)) #输出:TypeError : error message ### 重新抛出异常 def test_exception(): try: print(noname) except Exception as e: raise e #重新抛出异常,错误类型不变 try: test_exception() except NameError as e: print(e) ## assert语句 判断是否为真 >断言语句 : 如果为假,引发AssertionError错误 >语法格式: assert expression[,args] > args : 判断条件的描述信息 python3 实例 ```python try: a='98' assert (isinstance(a,int)), ' is\'not int!' except AssertionError as e: print("AssertionError:",e) #输出 AssertionError:is'not int ``` ## 自定义异常类 ```python class CustomError (Exception): def __init__(self,info): Exception.__init__(self) self.errorinfo=info def __str__(self): return "CustomError:%s" % self.errorinfo try: raise CustomError("test custom Error") except CustomError as e: print("Error:",e) #输出 CustomError:test custom Error ```