在python中,如果想手动引发一个异常,我们一般都会使用raise

# -*- coding:utf-8 -*-
# @Author: WanMingZhu
# @Date: 2019/10/22 10:31
try:
1 / 0
except ZeroDivisionError as e:
raise RuntimeError("error occurred")
"""
Traceback (most recent call last):
File "C:/Users/satori/Desktop/satori/task.py", line 5, in <module>
1 / 0
ZeroDivisionError: division by zero During handling of the above exception, another exception occurred: Traceback (most recent call last):
File "C:/Users/satori/Desktop/satori/task.py", line 7, in <module>
raise RuntimeError("error occurred")
RuntimeError: error occurred
"""

如果这样设置异常的话,During handling of the above exception, another exception occurred:,我们只是看到提示:在处理以上异常的时候,另一个异常产生了。如果我们使用raise .....from...的语法呢?

# -*- coding:utf-8 -*-
# @Author: WanMingZhu
# @Date: 2019/10/22 10:31
try:
1 / 0
except ZeroDivisionError as e:
raise RuntimeError("error occurred") from e
"""
Traceback (most recent call last):
File "C:/Users/satori/Desktop/satori/task.py", line 5, in <module>
1 / 0
ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: Traceback (most recent call last):
File "C:/Users/satori/Desktop/satori/task.py", line 7, in <module>
raise RuntimeError("error occurred") from e
RuntimeError: error occurred
"""

The above exception was the direct cause of the following exception:,会直接告诉我们上面异常是下面异常产生的直接原因。

因此我们可以看到两者的不同之处,from会为异常设置一个__cause__属性,表示异常是由谁直接引起的。处理异常的时候出现了新的异常,在不使用from的情况下,更倾向于新异常和旧异常之间没有关联,而from则是能够直接指出新异常是由旧异常直接引起的。这样的话,有助于对异常的分析和排查。但是from有个限制,那就是后面必须跟一个异常的类、或者实例、或者None

# -*- coding:utf-8 -*-
# @Author: WanMingZhu
# @Date: 2019/10/22 10:31
try:
1 / 0
except ZeroDivisionError as e:
raise RuntimeError("error occurred") from 123
"""
raise RuntimeError("error occurred") from 123
TypeError: exception causes must derive from BaseException
"""
# 提示我们必须from一个BaseException
# 这个BaseException是Exception的父类,Exception继承自BaseException
# -*- coding:utf-8 -*-
# @Author: WanMingZhu
# @Date: 2019/10/22 10:31
try:
1 / 0
except ZeroDivisionError as e:
raise RuntimeError("error occurred") from IndexError
"""
raise RuntimeError("error occurred") from 123
TypeError: exception causes must derive from BaseException
"""
# 这里是ZeroDivisionError,我可以手动用IndexError引发

但如果我在finally中引发异常

# -*- coding:utf-8 -*-
# @Author: WanMingZhu
# @Date: 2019/10/22 10:31
try:
1 / 0
except ZeroDivisionError as e:
pass finally:
raise Exception("xxxx")
"""
Traceback (most recent call last):
File "C:/Users/satori/Desktop/satori/task.py", line 10, in <module>
raise Exception("xxxx")
Exception: xxxx
"""

可以看到只出现了我们自己引发的异常,于是我们可以设置一个traceback

# -*- coding:utf-8 -*-
# @Author: WanMingZhu
# @Date: 2019/10/22 10:31
try:
1 / 0
except ZeroDivisionError as e:
import sys
tb = sys.exc_info()[2]
finally:
raise Exception("xxxx").with_traceback(tb)
"""
Traceback (most recent call last):
File "C:/Users/satori/Desktop/satori/task.py", line 10, in <module>
raise Exception("xxxx").with_traceback(tb)
File "C:/Users/satori/Desktop/satori/task.py", line 5, in <module>
1 / 0
Exception: xxxx
"""

通过这种方式,会自动帮我们定位到出现异常的语句。这里trackback就是引发异常语句的异常的trackback

我们目前一直在关联异常,那么可不可以禁止异常关联呢?显然是可以的。

# -*- coding:utf-8 -*-
# @Author: WanMingZhu
# @Date: 2019/10/22 10:31
try:
1 / 0
except ZeroDivisionError as e:
raise Exception("xxxx") from None
"""
Traceback (most recent call last):
File "C:/Users/satori/Desktop/satori/task.py", line 7, in <module>
raise Exception("xxxx") from None
Exception: xxxx
"""

只显示了我们自己定义的异常,没有出现During handling of the above exception, another exception occurred:这样的字眼了。

因此在异常处理中,python会为异常设置上下文。但我们也可以手动通过with_traceback()来设置上下文,或者通过from来指定异常是由谁引起的。这些手段都是为了得到更好的异常回溯信息,打印清晰的异常上下文。若忽略上下文,则可以通过raise ···· from···None来禁止自动显示异常上下文。

raise与raise······from的更多相关文章

  1. raise 与 raise ... from 的区别

    起步 Python 的 raise 和 raise from 之间的区别是什么? try: print(1 / 0) except Exception as exc: raise RuntimeErr ...

  2. python中raise的用法

    有关于python里raise显示引发异常的方法: 当程序出错时,python会自动触发异常,也可以通过raise显示引发异常 一旦执行了raise语句,raise之后的语句不在执行 如果加入了try ...

  3. Python错误调试-raise、assert

    raise: raise语句手工引发一个异常:,这样做程序不会因异常而终止,而是运行报错 1 "raise" [expression ["," expressi ...

  4. python 异常处理函数--raise

    Python 异常处理--raise函数用法 在Python中,要想引发异常,最简单的形式就是输入关键字raise,后跟要引发的异常的名称.异常名称标识出具体的类: Python异常处理是那些类的对象 ...

  5. 信号的发送kill,raise,alarm,setitimer,abort,sigqueue

    1.kill函数 int kill(pid_t pid, int sig); 发送信号给指定的进程. (1) If pid is positive, then signal sig is sent t ...

  6. python 基础 6.2 raise 关键字使用

    一. raise 关键字    raise 用来触发异常    语法如下:     raise[Exception [,args [,traceback]]]     语句中Exception 是异常 ...

  7. python raise a string exception is deprecated

    python不允许raise 一个内建的string 对象.所以就崩溃,可以先将其转换成其他string,比如赋值.

  8. 解决: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19

    错误信息:C:\Python27\lib\site-packages\sklearn\utils\validation.py:395: DeprecationWarning: Passing 1d a ...

  9. ORACLE RAISE

    ORACLE 出错信息的输出 偷懒的办法直接在Exception 后使用raise但是错误信息不是很完整使用RAISE_APPLICATION_ERROR(-20999, DBMS_UTILITY.f ...

随机推荐

  1. C语言JS引擎

    基础知识 SpiderMonkey 简介 和其他的 JavaScript 引擎一样,SpiderMonkey 不直接提供像 DOM 这样的对象,而是提供解析,执行 JavaSccript 代码,垃圾回 ...

  2. python基础知识(属性property)

    属性property property               !=          类属性和实例属性 访问计算后所得的值           返回所存储的值 创建用于计算的属性 @proper ...

  3. 架构模式: 服务前端的后端(BFF模式)

    架构模式: 服务前端的后端(BFF模式) 上下文 让我们假设您正在构建一个使用Microservice体系结构模式的在线商店,并且您正在实现产品详细信息页面.您需要开发产品详细信息用户界面的多个版本: ...

  4. iptables基本命令到深入

    1.关闭firewalld,安装iptables-server并启动服务 systemctl stop firewalld systemctl disable firewalld yun -y ins ...

  5. USACO 1.2 Broken Necklace

    断点是白色的情况在做题的时候完全没有想到呢... 看到了数据才发现这个问题$qwq$ /* ID:Starry21 LANG:C++ TASK:beads */ #include<iostrea ...

  6. 【计算机视觉】【并行计算与CUDA开发】OpenCV中GPU模块使用

    CUDA基本使用方法 在介绍OpenCV中GPU模块使用之前,先回顾下CUDA的一般使用方法,其基本步骤如下: 1.主机代码执行:2.传输数据到GPU:3.确定grid,block大小: 4.调用内核 ...

  7. 蓝鲸智云安装proxy和p-agent过程记录

    1.agent_setup_pro.sh: no such file or directory 2.参考:https://bk.tencent.com/s-mart/community/questio ...

  8. Ubuntu下安装Golong并用Vscode做IDE最有效方法,避免99%的坑 | 轻松学习GO

    最详细的教程,避开99%的坑,亲测有效 由于大部分教程都是win版本的,所以专门总结了一个linux版本的,其核心在于环境配置和插件安装,经历本人通宵7小时解决了这个问题,用自己的踩坑帮助大家避坑,希 ...

  9. 分库分表之后,id 主键如何处理

    基于数据库的实现方案 数据库自增 id 这个就是说你的系统里每次得到一个 id,都是往一个库的一个表里插入一条没什么业务含义的数据,然后获取一个数据库自增的一个 id.拿到这个 id 之后再往对应的分 ...

  10. ######<待随时补充>我的学习规划######

    一.关于Python 1.demo   一些基础实验,包含Python基础知识等,约300-500个 2.Python常见模块的了解学习,如 time datetime random 随机数 os 与 ...