Python – In Python, how do I construct an exception from another exception without throwing it?

In Python, how do I construct an exception from another exception without throwing it?… here is a solution to the problem.

In Python, how do I construct an exception from another exception without throwing it?

Consider this snippet:

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)

Is there a way to construct MyCustomException with all the initialization (setting __cause__ or whatever) that from e does for me, but without throwing it?

Solution

As far as I know, there is no other way but to set up __cause__ manually.

But since you created a custom exception, this might help:

class MyCustomException(Exception):
    def __init__(self, cause=None)
        self.__cause__ = cause

Related Problems and Solutions