given function with exception inside. if the exception does not occur, then the function continues. How to start the function again, if the exception falls?

  • try: pass expect: def_name () - Nitive
  • one
    right in the function you should not make a recursive call, better make a wrapper for this function, i.e. You call a wrapper in which you catch the exception of the original function. If an exception is caught - rerun the function call, if again an exception - then throw it further. And catching exceptions and recursion can lead to endless reksii. As an option - to use recursion, but additionally pass the flag parameter (by default False, by repeated call you pass True) - if the parameter is True, then you do not handle the exception, otherwise the function call is repeated - BOPOH
  • I expected (on php) exceptions, and gave several chances to perform the function, i.e. I had a rough code like this: def func (): pass def wrapper (): repeatCount = 10 for i in xrange (repeatCount): try: func () break catch Exception, e: pass if the function threw an exception, then it was called again. If again there was an exception - again a call and so several times. Just do not forget to pause between calls, so that during repeated calls do not take up CPU time - BOPOH

2 answers 2

try_repeat is a decorator that repeats a function call if it threw an exception. exception_func - a function that, with a probability of 50%, will throw an exception

def try_repeat(func): def wrapper(*args, **kwargs): count = 10 while count: try: return func(*args, **kwargs) except Exception as e: print('Error:', e) count -= 1 return wrapper @try_repeat def exception_func(): import random if random.randint(0, 1): raise Exception('!!!') exception_func() 
  • It is worth mentioning that it is premature to use the decorator in this case: there can be various requirements in different cases (what exceptions to catch, how many times to repeat and under what conditions to repeat, add a pause or immediately run, whether to perform any actions in case of an exception ) entry in the log and so on. the code for each specific case is relatively easy to write and read, looking at try_repeat() decorator is not clear how these options are selected, so you should start with the simplest code that solves a problem regarded for Vai case - jfs
  • ... and only in the case of similar requirements in different places of the project, consider how to reuse the code. - jfs
 u@net13:~> cat 000.py #!/usr/bin/env python3 def input_val(): try: a=int(input("Введите значение: ")) print (a) except ValueError: print ("Требуется ввести числовое значение") input_val() else: print ("Отлично!") input_val() 

Will be executed until a numeric value is entered.