Catch multiple exceptions in one line (except block)

前端 未结 5 1934
故里飘歌
故里飘歌 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 04:09

    If you frequently use a large number of exceptions, you can pre-define a tuple, so you don't have to re-type them many times.

    #This example code is a technique I use in a library that connects with websites to gather data
    
    ConnectErrs  = (URLError, SSLError, SocketTimeoutError, BadStatusLine, ConnectionResetError)
    
    def connect(url, data):
        #do connection and return some data
        return(received_data)
    
    def some_function(var_a, var_b, ...):
        try: o = connect(url, data)
        except ConnectErrs as e:
            #do the recovery stuff
        blah #do normal stuff you would do if no exception occurred
    

    NOTES:

    1. If you, also, need to catch other exceptions than those in the pre-defined tuple, you will need to define another except block.

    2. If you just cannot tolerate a global variable, define it in main() and pass it around where needed...

提交回复
热议问题