Better syntax for re-raising an exception only if an exception occurred?

exception, python

Solution

Raise the exception in the except handler:

try:
    # do something that *might* raise an exception
except Exception:
    raise
finally:
    # something I *always* want to run

The `finally` suite is always going to be executed wether or not you re-raised the exception.

From the documentation:

If `finally` is present, it specifies a ‘cleanup’ handler. The `try` clause is executed, including any `except` and `else` clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The `finally` clause is executed. If there is a saved exception it is re-raised at the end of the `finally` clause.

Note that if the `finally` suite uses a `break` or `return` statement, the saved exception is discarded:

If the `finally` clause executes a return or break statement, the saved exception is discarded:

def f():
    try:
        1/0
    finally:
        return 42

>>> f()
42

but if you issue a `break`, `continue` or `return` in the `try` suite, the `finally` suite is executed still:

When a `return`, `break` or `continue` statement is executed in the `try` suite of a `try`...`finally` statement, the `finally` clause is also executed ‘on the way out.’

Note that before Python 2.5, you could not even combine `except` and `finally` suites in the same `try` statement; see PEP 341: Unified try/except/finally. Instead, you were expected to nest `try` statements:

try:
    try:
        # some code that could raise an exception
    except SomeException:
        # exception handler
finally:
    # cleanup code, always executed

Problem

I find myself doing this when I want to catch an exception, always run some specific code, then re-raise the original exception: ``` try: error = False # do something that *might* raise an exception except Exception: error = True finally: # something I *always* want to run if error: raise ``` I am using the flag because calling `raise` without a previous exception raises a `TypeError`. Is there a more Pythonic way to do with without the flag?

Original source