How to execute something if any exception happens

You can do this with a nested try. The except block of the outer try should catch all exceptions. Its body is another try that immediately re-raises the exception. The except blocks of the inner try actually handle the individual exceptions. You can use the finally block in the inner try to do what you want: run something after any exception, but only after an exception.

Here is a little interactive example (modeled on Applesoft BASIC for nostalgia purposes).

try:
    input("]")  # for Python 3: eval(input("]"))
except:
    try:
       #Here do something if any exception was thrown.
       raise
    except SyntaxError:
       print "?SYNTAX",
    except ValueError:
       print "?ILLEGAL QUANTITY",
    # additional handlers here
    except:
       print "?UNKNOWN",
    finally:
       print "ERROR"

I just tried a couple different idea's out and it looks like a flag is your best bet.

  • else suite is only called if there is no exception
  • finally will always be called

Actually I don't like flags and consider them as the last resort solution. In this case I'd consider something like this:

def f():
  try:
    do_something()
  except E1:
    handle_E1()
  except E2:
    handle_E2()
  else:
    return
  do_stuff_to_be_done_in_case_any_exception_occurred()

Of course, this is only an option if you can return in the else: case.

Another option might be to rethrow the exception and recatch it for a more general handling of errors. This might even be the cleanest approach:

def f():
  try:  # general error handling
    try:  # specific error handling
      do_something()
    except E1:
      handle_E1()
      raise
    except E2:
      handle_E2()
      raise
  except (E1, E2):
    do_stuff_to_be_done_in_case_any_exception_occurred()