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()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With