Raise two errors at the same time

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

    You can Raise more than one exception like this:

    try:
        i = 0
        j = 1 / i
    except ZeroDivisionError:
        try:
            i = 'j'
            j = 4 + i
        except TypeError:
            raise ValueError
    

    NOTE: it may be that only the ValueError is raised but this error message seems right:

    Traceback (most recent call last):
      File "", line 3, in 
        j = 1 / i
    ZeroDivisionError: division by zero
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "", line 7, in 
        j = 4 + i
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "", line 9, in 
        raise ValueError
    ValueError
    

提交回复
热议问题