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
>>>