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

前端 未结 3 1477
不思量自难忘°
不思量自难忘° 2020-12-11 10:17

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()<

3条回答
  •  无人及你
    2020-12-11 10:38

    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

提交回复
热议问题