5.4 Additional Clauses#

An else clause#

If the try-block runs without raising any exception, any except clauses in it are skipped and the entire try-catch is finished. But if there is something we want to do specifically in that case, we can add an else clause after all the except clauses. The code in the else clause is executed if the try-block runs without raising any exception.

Here’s an example:

def gibberish(d: dict[int: str], num: int) -> None:
    try:
        k = int(len(d) / num)
        answer = d[k]
        print(f'The answer is {answer}')
    except ZeroDivisionError:
        print(f'Cannot divide by zero!')
    except KeyError:
        print(f'Key {k} does not exist!')
    else:
        print('No problems occurred.')

The else clause executes only if no kind of exception is raised. If a ZeroDivisionError or KeyError is raised, or even if another kind of exception not handled by an except clause is raised, the else clause is skipped. Think of the else clause as saying “else if there was no exception at all, …” (and not “else if there was some other kind of exception …”).

A finally clause#

There is one last option: we can add a finally clause. The code in this clause is executed no matter what: whether or not an exception was raised, or if one was raised, whether or not it was handled by an except clause. The designers of Python intended it for taking care of any clean-up step(s) that should happen under all circumstances.

Here we’ve added a finally to our gibberish function:

def gibberish(d: dict[int: str], num: int) -> None:
    try:
        k = int(len(d) / num)
        answer = d[k]
        print(f'The answer is {answer}')
    except ZeroDivisionError:
        print(f'Cannot divide by zero!')
    except KeyError:
        print(f'Key {k} does not exist!')
    else:
        print('No problems occurred.')
    finally:
        print('Regardless, here we are.')

The “Regardless” statement is printed no matter what happens:

>>> gibberish_v2({6: 'twas', 2: 'brillig', 15: 'slithy', 3: 'toads'}, 2)
The answer is brillig
No problems occurred.
Regardless, here we are.
>>> gibberish_v2({6: 'twas', 2: 'brillig', 15: 'slithy', 3: 'toads'}, 0)
Cannot divide by zero!
Regardless, here we are.
>>> gibberish_v2({6: 'twas', 2: 'brillig', 15: 'slithy', 3: 'toads'}, 3)
Key 1 does not exist!
Regardless, here we are.