Raise two errors at the same time

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

    Yes, you can handle more than one error, either using

    try:
        # your code here
    except (ValueError, KeyError) as e:
        # catch it, the exception is accessable via the variable e
    

    Or, directly add two "ways" of handling different errors:

    try:
        # your code here
    except ValueError as e:
        # catch it, the exception is accessable via the variable e
    except KeyError as e:
        # catch it, the exception is accessable via the variable e
    

    You may also leave out the "e" variable.

    Checkout the documentation: http://docs.python.org/tutorial/errors.html#handling-exceptions

提交回复
热议问题