在Python中,如何在不提高异常的情况下从另一个异常构造异常?

问题描述 投票:2回答:1

请考虑以下代码段:

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__或其他什么),但没有抛出它?

python exception exception-handling
1个回答
3
投票

AFAIK,除了手动设置__cause__之外别无他法。

但是,由于您创建了自定义异常,因此这可能会有所帮助:

class MyCustomException(Exception):
    def __init__(self, cause=None)
        self.__cause__ = cause
© www.soinside.com 2019 - 2024. All rights reserved.