raise和raise from捕获异常
参考:Python 中 raise 和 raise/from 的区别_python raise from_团子大圆帅的博客-CSDN博客
raise 与 raise ... from 的区别 - 知乎 (zhihu.com)
Python | raise...from... 是个什么操作?_小詹学 Python的博客-CSDN博客
raise/from 捕获:打印异常上下文消息,指出新异常是由旧异常引起的,这样的异常之间的关联有助于后续对异常的分析和排查。(更规范)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | >>> try : ... a = 2 / 0 ... except Exception as e: ... raise Exception( '分母不能为0' ) from e ... Traceback (most recent call last): File "<stdin>" , line 2 , in <module> ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<stdin>" , line 4 , in <module> Exception: 分母不能为 0 >>> |
raise from None:禁止/关闭自动显示异常上下文。
1 2 3 4 5 6 7 8 9 | >>> try : ... a = 2 / 0 ... except Exception as e: ... raise Exception( '分母不能为0' ) from None ... Traceback (most recent call last): File "<stdin>" , line 4 , in <module> Exception: 分母不能为 0 >>> |
raise自定义异常中捕获:可同时抛出自定义异常和原生异常,但是无法体现异常的关联
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | >>> try : ... a = 2 / 0 ... except Exception as e: ... raise Exception(f '分母不能为0,{e}' ) ... Traceback (most recent call last): File "<stdin>" , line 2 , in <module> ZeroDivisionError: division by zero During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>" , line 4 , in <module> Exception: 分母不能为 0 ,division by zero >>> |
只raise抛出原生异常:只抛出原生异常
1 2 3 4 5 6 7 8 9 10 | >>> try : ... a = 2 / 0 ... except Exception as e: ... raise e ... Traceback (most recent call last): File "<stdin>" , line 4 , in <module> File "<stdin>" , line 2 , in <module> ZeroDivisionError: division by zero >>> |
只raise自定义异常:可同时抛出自定义异常和原生异常,但是无法体现异常的关联
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | >>> try : ... a = 2 / 0 ... except Exception as e: ... raise Exception( '分母不能为0' ) ... Traceback (most recent call last): File "<stdin>" , line 2 , in <module> ZeroDivisionError: division by zero During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>" , line 4 , in <module> Exception: 分母不能为 0 >>> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决