2026/4/13 17:32:22
网站建设
项目流程
湖州 外贸网站建设,网站空间是先备案后买,免费下载软件的网站有哪些,wordpress 角色插件异常
异常(Exception):1.什么是异常#xff1f;python运行时#xff0c;发生的错误#xff0c;而导致程序最终无法执行#xff0c;异常#xff01;思考#xff1a;有没有出现错误#xff1f;编译过程中的错误#xff0c;红色波浪线运行过程中的错误 异常(Exception): 1.什么是异常 python运行时发生的错误而导致程序最终无法执行异常 思考有没有出现错误 编译过程中的错误红色波浪线 运行过程中的错误编译通过但是运行之后报错 补充: 特性运行时发生红色的错误终止程序 异常的父类BaseException 2.如何处理异常 try: 可能会出现问题的代码 except [抓取异常的类型 as e]: 处理的结果 示例#异常示例#1 分母不能为0print(运行前)try:res10/0#ZeroDivisionErrorprint(res)exceptZeroDivisionErrorase:print(e)print(运行后)#运行结果运行前 division by zero 运行后#2 文件不存在try:withopen(../exception/a.txt,r,encodingutf-8)asf:print(f.read())exceptFileNotFoundErrorase:print(e)print(读取后)#运行结果[Errno2]No suchfileordirectory:../exception/a.txt读取后#3 转换异常str1zhangsantry:resint(str1)exceptValueErrorase:print(e)print(转换后)#运行结果invalid literalforint()withbase10:zhangsan转换后处理异常 处理异常 1.异常的复杂格式 try: 可能会出现问题的代码 except [抓取异常类型 as 别名]: 处理代码 [else: 没有发生异常处理的代码 finally: 作用一般用来关闭文件或者释放资源的 异常的处理出口 ] 2.合并处理异常 -了解 try 异常代码 except (异常1异常2异常3......异常n) as e 3.处理多级异常 注意 except可以写多个分别抓取不同的异常信息 一般情况下异常处理的对象(范围越小异常信息更准确)越小越好 父异常一般写在子异常之后 异常的复杂格式#1 案例处理文件异常fNonetry:fopen(test.txt,r,encodingutf-8)resf.read()print(res)exceptExceptionase:print(文件找不到)else:print(当前正常)finally:print(程序正在执行finally块)iffisnotNone:#在写finally时需要加判断f.close()合并处理异常#2 合并异常格式try:res10/0#division by zerores2int(lisi)#ValueErrorexcept(ZeroDivisionError,ValueError)ase:print(e)多个异常处理#3 多个异常处理#案例读取文件内容转换为int再除以0try:fopen(test.txt,r,encodingutf-8)resint(f.read())resres/0print(res)exceptFileNotFoundErrorase:print(e)exceptValueErrorase:print(e)exceptZeroDivisionErrorase:print(e)exceptExceptionase:print(f不可预估的错误{e})案例——自定义异常 异常实现登录案例 自行抛出异常时需要使用raise #自定义异常classMyException(Exception):msgdef__init__(self,msg):self.msgmsg#模拟数据库的用户数据username_mysqlzhangsanpassword_mysql123deflogin(username,password):#1 用户名是否存在ifusername_mysql!username:#抛出一个自定义异常raiseMyException(用户不存在)#2.密码是否准确ifusernameusername_mysqlandpassword!password_mysql:raiseMyException(密码错误)#3 是否登录成功returnTrueif__name____main__:usernameinput(username: )passwordinput(password: )try:login(username,password)exceptExceptionase:print(e)else:print(ok)