I have a trouble to find the "pythonic" way to do this: I need to catch different blocks of code with the same try-except pattern. The blocks to catch are different from each other. Currently I am repeating the same try-except pattern in several points of the code with a long list of exceptions.
try:
block to catch
except E1, e:
log and do something
except E2, e:
log and do something
...
except Exception, e:
log and do something
There is a good way to solve this using the with statement and a context manager decorator:
from contextlib import contextmanager
@contextmanager
def error_handler():
try:
yield
except E1, e:
log and do something
...
except Exception, e:
log and do something
...
with error_handler():
block to catch
...
But, what happens if I need to know whether or not there has been an exception in the block? i.e. Is there any alternative to do something like the previous with block for try-except-else?
A use case example:
for var in vars:
try:
block to catch
except E1, e:
log and do something
# continue to the next loop iteration
except E2, e:
log and do something
# continue to the next loop iteration
...
except Exception, e:
log and do something
# continue to the next loop iteration
else:
do something else
Could I do something like that in a pythonic way to avoid repeat the same try-except pattern again and again?