简体   繁体   中英

How not to stop the execution of other function in python in case of Exception/Error

I have a script in python which works as shown below. Each function performs a completely different task and not related to each other. My problem is if function2() is having an issue during the execution process then function3() , function4() , function5() will not execute. I know you will say to handle this by catching the exception (try..except) but then i have to catch every exception which is not i am looking for. In a nutshell how do i code where my other functions are not impacted if any of the function is having issue. Ideally it should exclude that problematic function and let the other function to execute.

def function1():
    some code

def function2():
    some code

def function3():
    some code

def function4():
    some code

def function5():
    some code

if __name__ == '__main__':
    function1()
    function2()
    function3()
    function4()
    function5()

No need to write multiple try/except . Create a list of your function and execute them. For example, you code should be like:

if __name__ == '__main__':
    func_list = [function1, function2, function3, function4, function5]

    for my_func in func_list:
        try:
            my_func()
        except:
            pass

OR, create a decorator and add that decorator to each of your function. Check A guide to Python's function decorators . For example, your decorator should be like:

def wrap_error(func):
    def func_wrapper(*args, **kwargs):
        try:
           return func(*args, **kwargs)
        except:
           pass
    return func_wrapper

Now add this decorator with your function definition as:

@wrap_error
def function1():
    some code

Functions having this decorator added to them won't raise any Exception

As of Python 3.4, a new context manager as contextlib.suppress is added which as per the doc:

Return a context manager that suppresses any of the specified exceptions if they occur in the body of a with statement and then resumes execution with the first statement following the end of the with statement.

In order to suppress all the exceptions, you may use it as:

from contextlib import suppress

if __name__ == '__main__':

    func_list = [function1, function2, function3, function4, function5]

    for my_func in func_list:
        with suppress(Exception):  # `Exception` to suppress all the exceptions
            my_func()  # Any exception raised by `my_func()` will be suppressed

You can use exception and catch all sort of exceptions like this

if __name__ == '__main__':
    try:
        function1()
    except:
        pass
    try:
        function2()
    except:
        pass    
    try:
        function3()
    except:
        pass    
    try:
        function4()
    except:
        pass

for large number of functions you can use

func_dict = {
 func1 : {
     param1 : val
     param2 : val
   },
 func1 : {
     param1 : val
     param2 : val
   }
}

thus you can iterate over the keys of the dictionary for the function and iterate on the parameters

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