请考虑以下代码段:
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)
有没有办法构建MyCustomException与from e
为我做的所有初始化(设置__cause__
或其他什么),但没有抛出它?
AFAIK,除了手动设置__cause__
之外别无他法。
但是,由于您创建了自定义异常,因此这可能会有所帮助:
class MyCustomException(Exception):
def __init__(self, cause=None)
self.__cause__ = cause