5  Error Handling

5.1 Exceptions

When our program runs into an error, Python throws an Exception. There several different types of exceptions and they work as a way to communicate what went wrong. Sometimes we simply want to let the program crash because the problem is completely unexpected or because we do not have a good solution to deal with it at run time.

One of the language constructs to deal with errors in Python is try-except, which has this structure:

try:
    # do something
except SomeException:
    # handle the error
finally:
    # Optionally to something (always executed)
try:
    1 / 0
except Exception as err:
    print("something went wrong:", err)
finally:
    print("Cleaning up the mess, no matter what")
something went wrong: division by zero
Cleaning up the mess, no matter what
try:
    1 / 1
    print("all good")
except Exception as err:
    print("something went wrong:", err)
finally:
    print("Cleaning up the mess, no matter what")
all good
Cleaning up the mess, no matter what
Good practice Tip

Be as explicit as possible with your exceptions to avoid letting unexpected errors slip through.

We can catch explicit exceptions:

try:
    1 / 0
    print("all good")
except ZeroDivisionError as err:
    print("yeap, it sometimes happens, show must go on..")
yeap, it sometimes happens, show must go on..
Note

Exceptions are also used beyond errors as a more general kind of means of communication in the python language, for example, to signal that a generator has been used up.

5.2 Assertions

A common way to verify that our code is actually implementing the logic we have in mind is adding so-called “assertions”. Assertions are like checkpoints that will make our code fail (and interrupt the program execution) if a condition is not met.

It is common to use assertions to check intermediate steps as well as for writing tests (as we will see later).

Here’s the basic syntax:

assert some-contition, "message if condition is false"

For example:

assert 1 > 0, "This should never happen"
print("We got to this point")
We got to this point
assert 0 > 1, "0 > 1? in which world do you live?"

print("We got to this point")
AssertionError: 0 > 1? in which world do you live?

Notice two things:
First, we didn’t get to the print statement – the program execution was interrupted.
Second, we got an AssertionError, a particular type of exception that python uses to communicate we didn’t meet the assertion, which means we could handle it like any other exception:

try:
    assert 0 > 1, "0 > 1? in which world do you live?"
except AssertionError:
    print("No idea, but fine, carry on...")
    
print("We got to this point")
No idea, but fine, carry on...
We got to this point

5.3 Exercises

Take this dictionary:

ages = {
    "mark": 12,
    "lua": 32,
    "martin": 8,
    "mette": 41,
    "malte": 27
}

And this names:

names = "mark", "lua", "juan", "marco", "anna"

Write a program that iterates over the names and prints each name and age.
If the name is not present in the ages dictionary, print this message “name: NAME is missing”. At the end of the program, print the number of not found names and a list with the found names.