Catch multiple exceptions in one line (except block)

前端 未结 5 1938
故里飘歌
故里飘歌 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:44

    From Python Documentation:

    An except clause may name multiple exceptions as a parenthesized tuple, for example

    except (IDontLikeYouException, YouAreBeingMeanException) as e:
        pass
    

    Or, for Python 2 only:

    except (IDontLikeYouException, YouAreBeingMeanException), e:
        pass
    

    Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using as.

提交回复
热议问题