python raise用法

以下面一段代码为例:

# !/usr/bin/env python3
# -*- coding:utf8 -*-
"""test except"""
import os
import sys

if __name__ == '__main__':
    
    try:
        raise IndexError
    except Exception as e:
        raise ValueError
        # raise ValueError from e
        # raise ValueError from None

  若 raise ValueError 则获得:在抛出IndexError的同时出现ValueError

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    raise IndexError
IndexError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 12, in <module>
    raise ValueError
ValueError

  若 raise ValueError from e 则获得:抛出ValueError警告,直接原因是IndexError导致的

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    raise IndexError
IndexError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    raise ValueError from e
ValueError

  若 raise ValueError from None 则直接出现:ValueError,没有给出原因

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    raise ValueError from None
ValueError

  综上来看,raise ValueError from e 效果最好,方便定位到问题所在。

  当然,也可以不用raise ... from结构:

# !/usr/bin/env python3
# -*- coding:utf8 -*-
"""test except"""
import os
import sys

if __name__ == '__main__':
    
    try:
        raise IndexError
    except Exception as e:
        # raise ValueError
        str_e = str(e) + 'something wrong!'
        raise ValueError(str_e)
        # raise ValueError from None

  得出的结果:

Traceback (most recent call last):
  File "test.py", line 10, in <module>
    raise IndexError
IndexError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    raise ValueError(str_e)
ValueError: something wrong!

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2023-12-18 11:34  CodeRabbit_joion  阅读(20)  评论(0编辑  收藏  举报