Raise two errors at the same time

后端 未结 6 1203
一个人的身影
一个人的身影 2021-02-19 03:10

Is there any way to raise two errors at the same time by using try and except? For example, ValueError and KeyError.

How do I do that?

6条回答
  •  借酒劲吻你
    2021-02-19 03:52

    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)
    

提交回复
热议问题