Error Handling: try/except — Python

An exception is an error that appears while a program runs. Read a traceback (Python's error report) from the bottom: the exception's type and message, then…

A customer writes the quantity as "two" instead of "2". Your program runs int("two"), then stops completely with a ValueError. The next customer can't be served, only because of one word.

An error like that, which appears while a program is running, is called an exception. try/except is the way to catch it, so the program does not stop. Picture two cashiers at Mr. Darto's stall. The rigid cashier is a program with no try/except: faced with writing that cannot be read, this cashier does not know what to do and stops serving. The good cashier is a program with try/except. This cashier has a backup plan: "try to read the number; if I can't, ask the customer to write it again". Then the cashier continues with the next customer. In code, the "try" part goes in try, and the "if I can't" part goes in except.

Reading a traceback

This is the program from the story of the customer who wrote "two":

text = "two"
quantity = int(text)
print("Total:", 15 * quantity)

The program stops, and Python prints an error report called a traceback:

Traceback (most recent call last):
  File "/home/darto/stall.py", line 2, in <module>
    quantity = int(text)
ValueError: invalid literal for int() with base 10: 'two'

The exception types you will see most often:

try and except

Wrap the line that can fail in try, and write the backup plan in except:

text = "two"
try:
    quantity = int(text)
    print("Total:", 15 * quantity)
except ValueError:
    print("Quantity must be a number, not", text)
print("Cashier keeps serving")

The result depends on what text holds:

text What happens Output
"3" the try block runs to the end, except is skipped Total: 45, then Cashier keeps serving
"two" int(text) fails, the rest of try is skipped, except ValueError runs Quantity must be a number, not two, then Cashier keeps serving

You can also write try inside a function. There, an except block may use return to give back a replacement value:

def per_person(total, people):
    try:
        return total // people
    except ZeroDivisionError:
        return "Number of people can't be 0"

print(per_person(45, 3))      # 15
print(per_person(45, 0))      # Number of people can't be 0

This function uses //, not /. Remember from the operators lesson: / always gives a float. 10 / 2 is 5.0, while 45 // 3 is 15.

Several excepts, else and finally

Some customers want to split the bill: a total of $45 is shared equally among a number of people. The cashier types the number of people as text, and this program works out each person's share:

total = 45
text = "3"

try:
    people = int(text)
    per_person = total // people
except ValueError:
    print("Number of people must be a number, not", text)
except ZeroDivisionError:
    print("Number of people can't be 0")
else:
    print("Pay per person:", per_person)
finally:
    print("Cashier ready again")

The result for three values of text:

text What happens Output
"3" try succeeds, so else runs Pay per person: 15, Cashier ready again
"two" int fails: ValueError Number of people must be a number, not two, Cashier ready again
"0" 45 // 0 fails: ZeroDivisionError Number of people can't be 0, Cashier ready again

Now suppose except ZeroDivisionError is removed and text is "0". No except catches the ZeroDivisionError that appears, but finally still runs first. Only after that does the program stop:

Cashier ready again
Traceback (most recent call last):
  File "/home/darto/stall.py", line 6, in <module>
    per_person = total // people
                 ~~~~~~^^~~~~~~~
ZeroDivisionError: integer division or modulo by zero

raise and your own exceptions

Your own code can raise an exception too, with raise. In this example even the exception type is our own, OutOfStock:

class OutOfStock(Exception):
    pass

def take_toast(stock):
    if stock == 0:
        raise OutOfStock("toast is sold out")
    return stock - 1

try:
    take_toast(0)
except OutOfStock as e:
    print("Sorry,", e)       # Sorry, toast is sold out

⚠️ An except that catches too much, and a misunderstood finally

TL;DR: An exception is an error that appears while a program runs. Read a traceback (Python's error report) from the bottom: the exception's type and message, then the file and line. try: holds the code to attempt, and except SomeError: catches that type so the program continues. as e keeps that exception, with its message, in the variable e. Several except blocks are matched from the top. else runs only when try raised no exception, and finally always runs. The order is try, except, else, finally. For example, when try holds int("abc") and there are except ValueError and finally blocks, the message from the except block is printed, then the message from the finally block. raise raises an exception on purpose, and your own exception type is a child class of Exception, such as class OutOfStock(Exception). Catch specific types, not every exception.

⚡ Read a traceback from the bottom

Meaning: An error that appears while a program runs is called an exception. Python then prints a report called a traceback. The last line of a traceback holds the exception's type and its message, for example ValueError: invalid literal for int() with base 10: 'two'. Above it are the file name, the line number and the line that failed. The program stops at that line.

⚡ Try first, catch it if it fails

Write:

text = "two"
try:
    quantity = int(text)
    print("Total:", 15 * quantity)
except ValueError:
    print("Quantity must be a number, not", text)
print("Cashier keeps serving")
Guess first: does the line print("Total:", ...) inside try run?

No. As soon as int(text) fails, the rest of the try block is skipped and the except block runs.

Meaning: try: holds the code to attempt. except ValueError: catches an exception of the type ValueError, so the program doesn't stop and the last line still runs. Catch a specific type, not every exception.

⚡ else and finally

Guess first: a finally block is written last, after every except. When an exception isn't caught by any except, does the finally block still run?

It does. finally runs first, and only then does the program stop.

Meaning: else runs only when try finishes with no exception. finally always runs, so it is the place for clean-up, such as closing a file. The order is try, except, else, finally.

⚡ Raising your own exception

Write:

class OutOfStock(Exception):
    pass

def take_toast(stock):
    if stock == 0:
        raise OutOfStock("toast is sold out")
    return stock - 1

try:
    take_toast(0)
except OutOfStock as e:
    print("Sorry,", e)       # Sorry, toast is sold out

Meaning: raise raises an exception on purpose, and the text in its round brackets becomes the message. Your own exception is a child class of Exception. as e keeps that exception, with its message, in e.

What you will learn