I have a list of functions that may fail and, if one fails, I don't want the script to stop, but to continue with next function.
I am executing it with something like this :
list_of_functions = [f_a, f_b, f_c] for current_function in list_of_functions: try: current_function() except Exception: print(traceback.format_exc())
It's working fine, but it is not PEP8 compliant:
When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause.
For example, use:
try: import platform_specific_module except ImportError: platform_specific_module = None
A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException: ).
A good rule of thumb is to limit use of bare 'except' clauses to two cases:
If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred.
If the code needs to do some cleanup work, but then lets the exception propagate upwards with raise . try...finally can be a better way to handle this case.
How can I do this the good way?
As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
By raising a proper exception, it will allow other parts of your code to handle the exception properly, such that the execution can proceed. In the above code, we first define a function, read_data , that can read a file.
The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error.
The PEP8 guide you quote suggests that it is okay to use a bare exception in your case provided you are logging the errors. I would think that you should cover as many exceptions as you can/know how to deal with and then log the rest and pass
, e.g.
import logging list_of_functions = [f_a,f_b,f_c] for current_function in list_of_functions: try: current_function() except KnownException: raise except Exception as e: logging.exception(e)
Use this to cheat PEP8:
try: """code""" except (Exception,): pass
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