raise和raise from捕获异常
异常 from 捕获 RAISE
2023-09-14 09:01:11 时间
参考:Python 中 raise 和 raise/from 的区别_python raise from_团子大圆帅的博客-CSDN博客
raise 与 raise ... from 的区别 - 知乎 (zhihu.com)
Python | raise...from... 是个什么操作?_小詹学 Python的博客-CSDN博客
raise/from 捕获:打印异常上下文消息,指出新异常是由旧异常引起的,这样的异常之间的关联有助于后续对异常的分析和排查。(更规范)
>>> 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:禁止/关闭自动显示异常上下文。
>>> 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自定义异常中捕获:可同时抛出自定义异常和原生异常,但是无法体现异常的关联
>>> 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抛出原生异常:只抛出原生异常
>>> 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自定义异常:可同时抛出自定义异常和原生异常,但是无法体现异常的关联
>>> 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
>>>
相关文章
- Mysql 的异常:The last packet successfully received from the server was 90 milliseconds ago. The last packet sent successfully to the server was 43,603,303 milliseconds ago. is longer than the server con
- JAVA-JSP内置对象之exception对象用来处理错误异常
- 【Mysql异常】[HY000][1030] Got error 28 from storage engine
- "无法加载 DLL“oramts.dll”: 找不到指定的模块。 (异常来自 HRESULT:0x8007007E)。" —— 的解决方法
- SpringMvc的 @Valid 拦截到的异常如何抛出
- Python中常见的异常总结
- SAS信用评分之番外篇异常值的识别
- 【异常】MyBatis-Plus提示报错XML fragments parsed from previous mappers does not contain value for xxx
- 【异常】Dbeaver配置JDBC连接ES时提示SQL错误:current license is non-compliant for [jdbc]
- 【异常】Jenkins构建提示Could not read from remote repository.
- SLS机器学习最佳实战:日志聚类+异常告警 —— 这个就是splunk SQL+机器学习结合产物啊
- 聚类-异常检测
- Clojure 学习入门(17)- 异常处理