在 Python 中,如何在不引发异常的情况下从另一个异常构造异常?
In Python, how do I construct an exception from another exception without raising it?
考虑这个片段:
all_errors = []
for i in something:
try:
do_something_that_throws(i)
except Exception as e
# what I know I can do:
raise MyCustomException(i) from e
# what I actually want:
# all_errors.append(MyCustomException(i) from e)
有没有一种方法可以用 from e
为我做的所有初始化(设置 __cause__
或其他任何东西)构造 MyCustomException,但又不抛出它?
据我所知,除了手动设置 __cause__
别无他法。
但是由于您创建了自定义异常,这可能会有所帮助:
class MyCustomException(Exception):
def __init__(self, cause=None)
self.__cause__ = cause
考虑这个片段:
all_errors = []
for i in something:
try:
do_something_that_throws(i)
except Exception as e
# what I know I can do:
raise MyCustomException(i) from e
# what I actually want:
# all_errors.append(MyCustomException(i) from e)
有没有一种方法可以用 from e
为我做的所有初始化(设置 __cause__
或其他任何东西)构造 MyCustomException,但又不抛出它?
据我所知,除了手动设置 __cause__
别无他法。
但是由于您创建了自定义异常,这可能会有所帮助:
class MyCustomException(Exception):
def __init__(self, cause=None)
self.__cause__ = cause