Raise two errors at the same time

You could raise an error which inherits from both ValueError and KeyError. It would get caught by a catch block for either.

class MyError(ValueError, KeyError):
    ...

The question asks how to RAISE multiple errors not catch multiple errors.

Strictly speaking you can't raise multiple exceptions but you could raise an object that contains multiple exceptions.

raise Exception(
    [
        Exception("bad"),
        Exception("really bad"),
        Exception("really really bad"),
    ]
)

Question: Why would you ever want to do this?
Answer: In a loop when you want to raise an error but process the loop to completion.

For example when unit-testing with unittest2 you might want to raise an exception and keep processing then raise all of the errors at the end. This way you can see all of the errors at once.

def test_me(self):

    errors = []

    for modulation in self.modulations:
        logging.info('Testing modulation = {modulation}'.format(**locals()))

        self.digitalModulation().set('value', modulation)
        reply = self.getReply()

        try: 
            self._test_nodeValue(reply, self.digitalModulation())
        except Exception as e:
            errors.append(e)

    if errors:
        raise Exception(errors)

Tags:

Python