Multiple try codes in one block

后端 未结 6 1465
情书的邮戳
情书的邮戳 2020-12-04 12:59

I have a problem with my code in the try block. To make it easy this is my code:

try:
    code a
    code b #if b fails, it should ignore, and go to c.
    c         


        
6条回答
  •  独厮守ぢ
    2020-12-04 13:24

    Lets say each code is a function and its already written then the following can be used to iter through your coding list and exit the for-loop when a function is executed without error using the "break".

    def a(): code a
    def b(): code b
    def c(): code c
    def d(): code d
    
    for func in [a, b, c, d]:  # change list order to change execution order.
       try:
           func()
           break
       except Exception as err:
           print (err)
           continue
    

    I used "Exception " here so you can see any error printed. Turn-off the print if you know what to expect and you're not caring (e.g. in case the code returns two or three list items (i,j = msg.split('.')).

提交回复
热议问题