0

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?

  • wrap the function you want its errors to be ignored and continue in its own try/except block, on the except part you can just type `pass` or log the error message or something. – dopstar Apr 18 '17 at 07:33
  • do as @dopstar says and just call each function in its own `try` `except` – WhatsThePoint Apr 18 '17 at 07:35
  • Why not map your functions in a dict and and put the try/catch in a loop? Pseudo code: For every condition[n]; TRY to call function[n]; catch err; loop to next – Y12K Apr 18 '17 at 07:56

1 Answers1

1

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?

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

Community
  • 1
  • 1
mdegis
  • 2,078
  • 2
  • 21
  • 39