raise和raise from捕获异常

参考: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
>>>

  

 

posted @ 2023-04-19 12:46  垄上行  阅读(52)  评论(0编辑  收藏  举报