If I have the following structure:
try:
do_something_dangerous()
except Exception1:
handle_exception1()
handle_all_exceptions()
except Exception2:
handle_exception2()
handle_all_exceptions()
...
What is the most Pythonic way to call handle_all_exceptions
if I don't want to do it in every except
clause because I have lots of them? Maybe there is a simple way to determine if the exception occured or not inside finally
clause?
Simplest way I can think is nesting try statements:
try:
try:
do_something_dangerous()
except Exception1:
handle_exception1()
raise
except Exception2:
handle_exception2()
raise
except Exception:
handle_all_exceptions()
The bare raise
reraises the exception.
Another option is to catch all exceptions and do your own dispatching instead of using the try
statement for that:
try:
do_something_dangerous()
except Exception as e:
if isinstance(e, Exception1):
handle_exception1()
if isisntance(e, Exception2):
handle_exception2()
handle_all_exceptions()
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