Python: if error raised I want to stay in script

Viewed 113099

I am doing some practice problems from online with python and I have a question about how to stay in a script if an error is raised. For example, I want to read in values from prompt and compare them to a set integer value inside the script. The only problem is that when someone enters something other than a number 'int(value)' (ex. value = 'fs') raises an error and exits the script. I want to have it so if this happens I stay inside the script and ask for another value to be entered at the prompt.

7 Answers

if you are doing it as a function you can do it as a decorator of the function

def retry(func):
    def wrapper(*args,**kwargs):
        while True:
            try:
                return func(*args,**kwargs)
                
            except Exception as e:
                print(f"{e} running again") # or simply pass
    return wrapper

@retry 
def myfunction():
   if badthinghappend:
     raise Error
   return something 
Related