Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way of doing common actions for all catched exceptions

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?

like image 551
sanyassh Avatar asked Sep 19 '25 01:09

sanyassh


1 Answers

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()
like image 64
nosklo Avatar answered Sep 21 '25 16:09

nosklo