exception - How to prevent try catching every possible line in python? -
i got many lines in row may throw exception, no matter what, should still continue next line. how without individually try catching every single statement may throw exception?
try: this_may_cause_an_exception() but_i_still_wanna_run_this() and_this() and_also_this() except exception, e: logging.exception('an error maybe occured in 1 of first occuring functions causing others not executed. locals: {locals}'.format(locals=locals())) let's see above code, functions may throw exceptions, should still execute next functions no matter if threw exception or not. there nice way of doing that?
i dont wanna this:
try: this_may_cause_an_exception() except: pass try: but_i_still_wanna_run_this() except: pass try: and_this() except: pass try: and_also_this() except: pass i think code should still continue run after exception if exception critical (the computer burn or whole system messed up, should stop whole program, many small things exceptions thrown such connection failed etc.) don't have problems exception handling, in case i'm using 3rd party library throws exceptions small things.
after looking @ m4spy's answer, thought wouldn't possible, have decorator let every line in function execute if 1 of them raises exception.
something cool:
def silent_log_exceptions(func): @wraps(func) def _wrapper(*args, **kwargs): try: func(*args, **kwargs) except exception: logging.exception('...') some_special_python_keyword # causes continue executing next line return _wrapper or this:
def silent_log_exceptions(func): @wraps(func) def _wrapper(*args, **kwargs): line in func(*args, **kwargs): try: exec line except exception: logging.exception('...') return _wrapper @silent_log_exceptions def save_tweets(): = requests.get('http://twitter.com) x = parse(a) bla = x * x
for func in [this_may_cause_an_exception, but_i_still_wanna_run_this, and_this, and_also_this]: try: func() except: pass there 2 things notice here:
- all actions want perform have represented callables same signature (in example, callables take no arguments). if aren't already, wrap them in small functions,
lambdaexpressions, callable classes, etc. - bare
exceptclauses bad idea, knew that.
an alternative approach, more flexible, use higher-order function like
def logging_exceptions(f, *args, **kwargs): try: f(*args, **kwargs) except exception e: print("houston, have problem: {0}".format(e))
Comments
Post a Comment