简体   繁体   中英

Call different function based on condition in try catch block in Python

I have a code where I am supposed to call different functions based on conditions. Below is my code

try:
    if condition_1 is True:
        function1()
    if condition_2 is True:
        function2()
    if condition_3 is True:
        function3()

except Exception, e:
    raise e

There are cases when multiple conditions can be true. So multiple function needs to be called and executed. It worked fine until today when 1 of the function raised an exception.

condition_1 and condition_3 were true. So function1 and function3 were supposed to be executed. When it called function1 , because of some error in function1 , it raised an exception, without executing function3 . What I wanted, is that even if function1 raises error, it should still continue and check other conditions and execute respective functions accordingly.

1 way to resolve this is to write each if condition in separate try/catch block. But, is there a better way to resolve this?

In my opinion, exceptions must be allowed to the interrupt the process if anything goes wrong in the way. However, you can achieve this behavior by removing raise keyword.

try:
    if condition_1 :
        function1()
    if condition_2 :
        function2()
    if condition_3 :
        function3()
except Exception, e:
    pass

Please take a look at Why is “except: pass” a bad programming practice?

PS: You do not need to check if True is True in conditions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM