IntermediateLesson 12 of 306 min read

Errors and exceptions: try, except and raise

Handle errors gracefully with try, except, else and finally, raise your own exceptions and debug problems calmly.

In this lesson you will

  • Recognise common exceptions
  • Use try, except, else and finally
  • Raise and define your own exceptions
  • Debug calmly with repr and breakpoints

About 20 minutes

Things go wrong. Plan for it.

The file you expected is missing. The user types a word where a number should go. The network drops. A list is empty when you try to take its first item. None of these are bugs in your logic; they are facts of life. Professional programs do not pretend errors will not happen. They expect them, handle them politely, and keep running. This lesson teaches you how.

What an error looks like

numbers = [10, 20, 30]
print(numbers[5])
Traceback (most recent call last):
  ...
IndexError: list index out of range

When something goes wrong, Python raises an exception and, unless you catch it, the program stops. The message names the kind of exception and what happened. Here are the ones you will meet most often:

Exception Typical cause
ValueError Right type, wrong value: int("abc")
TypeError Wrong type: "5" + 3
NameError A name that does not exist
IndexError A list position that does not exist
KeyError A dictionary key that does not exist
FileNotFoundError A file that is not there
ZeroDivisionError Dividing by zero
AttributeError Asking an object for something it does not have

try and except

try:
    age = int("twenty")
    print("You are", age)
except ValueError:
    print("That is not a number. Please type digits.")

print("The program carries on")
That is not a number. Please type digits.
The program carries on

Python tries the indented block under try. If an exception happens, it jumps straight to the matching except block and carries on from there. If nothing goes wrong, the except block is skipped. The rest of the program is never interrupted.

Catching specific errors

def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        print("Cannot divide by zero")
        return None
    except TypeError:
        print("Both values must be numbers")
        return None

print(safe_divide(10, 2))
print(safe_divide(10, 0))
print(safe_divide(10, "x"))
5.0
Cannot divide by zero
None
Both values must be numbers
None

Name the exceptions you expect. Avoid a bare except: with nothing after it, which catches everything including mistakes you would want to know about, such as typos. If you must catch a wide range, use except Exception as e: and look at e.

try:
    data = {"name": "Sara"}
    print(data["email"])
except Exception as e:
    print("Something went wrong:", type(e).__name__, "-", e)
Something went wrong: KeyError - 'email'

else and finally

def read_number(text):
    try:
        n = int(text)
    except ValueError:
        print(f"'{text}' is not a number")
    else:
        print(f"Good, {n} doubled is {n * 2}")     # only if no error
    finally:
        print("--- done ---")                      # always runs

read_number("21")
read_number("hello")
Good, 21 doubled is 42
--- done ---
'hello' is not a number
--- done ---
  • else runs only if the try block had no error.
  • finally runs always, whether or not there was an error. Perfect for cleanup, like closing a connection.

A friendly input loop

def ask_for_age():
    while True:
        text = input("How old are you? ")
        try:
            age = int(text)
        except ValueError:
            print("Please type digits only.")
            continue
        if age < 0 or age > 120:
            print("That does not look right.")
            continue
        return age

print("Age accepted:", ask_for_age())
How old are you? abc
Please type digits only.
How old are you? -5
That does not look right.
How old are you? 34
Age accepted: 34

This is one of the most useful patterns you will write. The loop keeps asking, the try/except handles letters, and the second check handles impossible numbers. The rest of your program can trust that age is a sensible integer.

Raising your own exceptions

def withdraw(balance, amount):
    if amount <= 0:
        raise ValueError("Amount must be above zero")
    if amount > balance:
        raise ValueError("Not enough money")
    return balance - amount

try:
    print(withdraw(100, 30))
    print(withdraw(100, 150))
except ValueError as e:
    print("Error:", e)
70
Error: Not enough money

When a function receives something it cannot work with, raise an exception with a clear message. The code that called it decides what to do. This is much better than quietly returning a wrong answer.

Custom exceptions

class InsufficientFunds(Exception):
    """Raised when a withdrawal is bigger than the balance."""
    def __init__(self, balance, amount):
        super().__init__(f"Balance {balance} is less than {amount}")
        self.shortfall = amount - balance

try:
    raise InsufficientFunds(100, 130)
except InsufficientFunds as e:
    print(e)
    print("Short by", e.shortfall)
Balance 100 is less than 130
Short by 30

Errors and files together

from pathlib import Path

def load_names(filename):
    try:
        with open(filename, encoding="utf-8") as f:
            return [line.strip() for line in f if line.strip()]
    except FileNotFoundError:
        print(f"{filename} not found, starting with an empty list")
        return []

print(load_names("names.txt"))

Path("names.txt").write_text("Sara\nAli\n\nMina\n")
print(load_names("names.txt"))
names.txt not found, starting with an empty list
[]
['Sara', 'Ali', 'Mina']

Debugging: finding the unexpected

  1. Read the last line of the error first: the type and message.
  2. Find your line in the traceback: the last line that mentions your file.
  3. Print the values near the problem: print(repr(value)) shows hidden spaces and types.
  4. Test small pieces in the Python shell.
  5. Use the debugger: in VS Code, click beside a line number to set a breakpoint and press F5.
  6. Question assumptions: is that list really not empty? Is that value really a number?
value = " 42 "
print(value)
print(repr(value))          # shows the quotes and spaces exactly
print(type(value), len(value))
 42 
' 42 '
<class 'str'> 4

assert: checking your own assumptions

def average(numbers):
    assert len(numbers) > 0, "average() needs at least one number"
    return sum(numbers) / len(numbers)

print(average([4, 6, 8]))
try:
    average([])
except AssertionError as e:
    print("Assertion failed:", e)
6.0
Assertion failed: average() needs at least one number
Common mistake

Catching an error and doing nothing: except: pass. The problem is still there, but now invisible, and bugs hide for months. At the very least print or log the error, and catch only the exceptions you expect.

Practice

Write a function to_number(text) that returns the number as a float, or None if the text is not a valid number. Test it with “3.5”, “abc” and “”.

Show one possible answer
def to_number(text):
    try:
        return float(text)
    except ValueError:
        return None

for t in ["3.5", "abc", ""]:
    print(repr(t), "->", to_number(t))
'3.5' -> 3.5
'abc' -> None
'' -> None
Practice

Ask for two numbers and divide the first by the second. Handle both invalid input and division by zero, with a friendly message for each.

Hint: Two except blocks, one per kind of problem.

Show one possible answer
try:
    a = float(input("First: "))
    b = float(input("Second: "))
    print("Result:", a / b)
except ValueError:
    print("Please type numbers only.")
except ZeroDivisionError:
    print("The second number cannot be zero.")
First: 8
Second: 0
The second number cannot be zero.
Ask forgiveness, not permission

Python programmers often just try something and handle the failure, rather than checking every condition first. It is shorter, and it also avoids a race where the situation changes between your check and your action.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does try / except do?

  1. Repeats code
  2. Catches an exception so the program can carry on
  3. Defines a function
  4. Speeds up code

It handles errors gracefully.

Which exception does int("abc") raise?

  1. TypeError
  2. NameError
  3. ValueError
  4. KeyError

The type is right, but the value is not a valid number.

When does the finally block run?

  1. Always
  2. Only on error
  3. Only on success
  4. Never

finally runs whether or not an error occurred.

Which keyword raises your own exception?

  1. throw
  2. error
  3. raise
  4. fail

Use raise ValueError(“message”).

Why avoid a bare except: pass?

  1. It hides every error, including real bugs
  2. It is slower
  3. It is invalid
  4. It stops the program

Catch specific exceptions and report them.

Summary

  • Exceptions stop a program unless you catch them.
  • Catch specific exceptions in except blocks.
  • finally always runs; else runs on success.
  • raise signals a problem clearly.

Next lesson

Next: modules, packages and pip, using code that other people wrote.

Questions

Should I wrap everything in try/except?

No. Wrap the risky operations (files, network, conversions) and handle errors where you can do something useful.

What is a traceback?

The list of calls that led to the error, printed when an exception is not caught. Read it from the bottom up.

How do I see the exception message?

Use except SomeError as e: and print(e).

Progress is saved in this browser.