Home > database >  Stop running a chain of functions in Python if an exception is triggered in one of the earlier funct
Stop running a chain of functions in Python if an exception is triggered in one of the earlier funct

Time:06-06

I have a set of functions which, are being called one after another depending on user input. I'm using this code to run the functions:

      #Run Multiple Functions
      def MultipleFunctions(*funcs):
          def MultipleFunctions(*args, **kwargs):
              for f in funcs:
              f(*args, **kwargs)
      return MultipleFunctions

I am calling the functions with command lines tied to tkinter objects. For instance:

      Op1 = OptionMenu(MainForm, Type, *Options, command=MultipleFunctions(Func1, Func2, Func3, Func4))

Func1 to 4 run various simple checks mostly to catch illegal option selections. For example Func1 checks the input of an edit box:

      #Check SideA Box Length is Valid
      def Func1(event):
          try:
             float(SideA.get())
          except ValueError:
              messagebox.showerror(message="This box only accepts numbers between 0 and 100")
              SideA.focus()
          if float(SideA.get()) > 100:
              messagebox.showerror(message="This box only accepts numbers between 0 and 100")
              SideA.focus()

What I want to do is break out of the Multiple Functions routine if an exception is triggered in say Func1. At the moment it runs all four functions regardless.

Can somebody point me in the right direction please?

Thank you

CodePudding user response:

You code is handling exception in except block.

There are few ways on how to stop execution if exception pops up.

  1. You can not handle exception and it'll interrupt program just by itself.
  2. You can rethrow exception after handling it in 'except' block.
  3. You can return a bool value as a success indicator from your function and add code to either continue or stop your loop in MultipleFunctions based on return value.

CodePudding user response:

Add a try-except around the function call and add a break statement to quit the loop.

Notice: in the decorator don't use the same function's name

def MultipleFunctions(*funcs):
    def wrapper(*args, **kwargs):
        for f in funcs:
            try:
                f(*args, **kwargs)
            except Exception as e:
                print(e)
                break # <- quit the loop
    return wrapper

def a(): print('a()')
def b(): print('b()')
def c(): print('c()')

# here without exceptions
MultipleFunctions(a, b, c)()
#a()
#b()
#c()

# here with exception: none of the function accept arguments!
MultipleFunctions(a, b, c)(2)
#a() takes 0 positional arguments but 1 was given

Further you need to reimplement the body of the function to raise exceptions:

def Func1(x): # similar to the Func1!
    if isinstance(x, float) or isinstance(x, int):
        if x > 100:
            raise Exception('Error, >100!')
        print('good')
    else:
        raise Exception('Error, not a number')

# to make it compatible with my example they need to be modify like this
def a(*args): print('a()')
def b(*args): print('b()')
def c(*args): print('c()')


MultipleFunctions(a, b, Func1, c)(1113)
#a()
#b()
#Error, >100!

MultipleFunctions(a, b, Func1, c)('smt')
#a()
#b()
#Error, not a number

MultipleFunctions(a, b, Func1, c)(10)
#a()
#b()
#good
#c()
  • Related