当前位置: 首页 > news >正文

python 异常处理详解带(3分钟速通)

1.  异常处理的基本结构

异常处理的基本结构包括 try 块和 except 块。try 块中放置可能引发异常的代码,而 except 块则用于捕获和处理这些异常。

try:  # 尝试执行的代码  pass  
except ExceptionType as e:  # 如果在try块中引发了ExceptionType异常,则执行这里的代码  print(f"捕获到异常:{e}")

2.  捕获多种异常

你可以使用多个 except 块来捕获不同类型的异常,或者使用单个 except 块来捕获多种异常(通过指定异常类的元组)。

try:  # 尝试执行的代码  pass  
except ValueError as e:  print(f"捕获到ValueError异常:{e}")  
except (TypeError, ZeroDivisionError) as e:  print(f"捕获到TypeError或ZeroDivisionError异常:{e}")

3.  捕获所有异常

使用 except Exception as e 可以捕获除了程序退出异常(如 SystemExit 和 KeyboardInterrupt)之外的所有异常。

try:  # 尝试执行的代码  pass  
except Exception as e:  print(f"捕获到异常:{e}")

4.  使用 else 和 finally

  • else 块:如果没有异常发生,则执行 else 块中的代码。
  • finally 块:无论是否发生异常,finally 块中的代码都会被执行。这通常用于执行清理操作,如关闭文件或释放资源。
try:  # 尝试执行的代码  pass  
except Exception as e:  print(f"捕获到异常:{e}")  
else:  print("没有异常发生")  
finally:  print("执行清理操作")

5.  实战案例

案例 1:处理除零错误
try:  result = 10 / 0  
except ZeroDivisionError as e:  print(f"捕获到除零错误:{e}")
案例 2:处理文件读写错误
try:  with open('nonexistent_file.txt', 'r') as file:  content = file.read()  
except FileNotFoundError as e:  print(f"文件未找到:{e}")  
except Exception as e:  print(f"发生其他错误:{e}")
案例 3:使用 else 和 finally
try:  # 假设这里有一些成功的操作  print("操作成功")  
except Exception as e:  print(f"捕获到异常:{e}")  
else:  print("没有异常发生,执行else块")  
finally:  print("执行清理操作")


http://www.mrgr.cn/news/5107.html

相关文章:

  • 大数据与大模型技术赋能:革新智能客服系统知识库管理的策略与实践
  • 【具体数学 Concrete Mathematics】1.1 递归问题 讲义
  • GitHub 官方 CLI 客户端发布 2.55.0
  • 软件测试-自动化测试
  • vue实现卡片遮罩层交互式功能
  • 倍内菲新品发布揭示宠物营养新纪元,引领行业保驾护航
  • 什么是天线OTA,怎么通过OTA数据评估产品射频环境情况
  • 004快速排序-python实现
  • FFmpeg的入门实践系列三(基础知识)
  • Docker微服务实战Demo
  • 自动化测试框架pytest+allure+requests
  • (待更)将windows11配置成生产力高的电脑:当计算机新生的你拿到新电脑时该配置哪些东西(python、mysql、git)
  • Linux基础I/O之文件缓冲区
  • 无人驾驶,并非无人之地
  • MFC在对话框中实现打印和打印预览
  • 配置ROS环境
  • 深度剖析C++string(上篇)
  • 瑞吉外卖--登录退出功能的实现
  • 在 uboot 中实现 UDP 协议
  • 记Windows文件右键扩展二级子菜单