Raise two errors at the same time

后端 未结 6 1204
一个人的身影
一个人的身影 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:50

    The solution from @shrewmouse still requires to choose an exception class to wrap the caught exceptions.

    • Following solution uses Exception Chaining via finally to execute code after one exception occurs
    • We don't need to know beforehand, what exceptions occur
    • Note that only the first exception that occurs can be detected from the caller via except
      • if this is a problem, use @Collin's solution above to inherit from all collected exceptions
    • You'll see the exceptions separated by:
      "During handling of the above exception, another exception occurred:"
    def raise_multiple(errors):
        if not errors:  # list emptied, recursion ends
            return
        try:
            raise errors.pop()  # pop removes list entries
        finally:
            raise_multiple(errors)  # recursion
    

    If you have a task that needs to be done for each element of a list, you don't need to collect the Exceptions beforehand. Here's an example for multiple file deletion with multiple error reporting:

    def delete_multiple(files):
        if not files:
            return
        try:
            os.remove(files.pop())
        finally:
            delete_multiple(files)
    

    PS:
    Tested with Python 3.8.5
    To print full traceback per exception have a look at traceback.print_exc
    The original question is answered since years. But as this page is the top search result for "python raise multiple" I share my approach to fill an (IMHO relevant) gap in the solution spectrum.

提交回复
热议问题