Catch multiple exceptions in one line (except block)

前端 未结 5 1932
故里飘歌
故里飘歌 2020-11-22 03:41

I know that I can do:

try:
    # do something that may fail
except:
    # do this if ANYTHING goes wrong

I can also do this:



        
5条回答
  •  名媛妹妹
    2020-11-22 03:58

    From Python documentation -> 8.3 Handling Exceptions:

    A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:

    except (RuntimeError, TypeError, NameError):
        pass
    

    Note that the parentheses around this tuple are required, because except ValueError, e: was the syntax used for what is normally written as except ValueError as e: in modern Python (described below). The old syntax is still supported for backwards compatibility. This means except RuntimeError, TypeError is not equivalent to except (RuntimeError, TypeError): but to except RuntimeError as TypeError: which is not what you want.

提交回复
热议问题