Catch multiple exceptions in one line (except block)

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

    One of the way to do this is..

    try:
       You do your operations here;
       ......................
    except(Exception1[, Exception2[,...ExceptionN]]]):
       If there is any exception from the given exception list, 
       then execute this block.
       ......................
    else:
       If there is no exception then execute this block. 
    

    and another way is to create method which performs task executed by except block and call it through all of the except block that you write..

    try:
       You do your operations here;
       ......................
    except Exception1:
        functionname(parameterList)
    except Exception2:
        functionname(parameterList)
    except Exception3:
        functionname(parameterList)
    else:
       If there is no exception then execute this block. 
    
    def functionname( parameters ):
       //your task..
       return [expression]
    

    I know that second one is not the best way to do this, but i'm just showing number of ways to do this thing.

提交回复
热议问题