Error Handling in Python: try and except

Lesson 2 of 6 · ·

Programs meet bad input all the time: a zero where you divide, a missing file, a word where a number should be. Without error handling, the first one stops everything. Python try except lets you catch the errors you expect, deal with them, and carry on. This lesson covers the four parts of the statement and ends with a worked example you can adapt.

Playing loads the video from YouTube. Watch on YouTube

The basic try and except

Put the code that might fail in the try block. If it raises an error, Python jumps to the except block instead of crashing.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error: the denominator can't be 0.")
Error: the denominator can't be 0.

Name the error you expect. A bare except: catches everything, including typing mistakes in your own code and the Ctrl+C that someone presses to stop the program, which hides real bugs.

Handling different errors differently

One try can have several except blocks. Python runs the first one that matches the error.

even_numbers = [2, 4, 6, 8]
try:
    print(even_numbers[5])
except ZeroDivisionError:
    print("Denominator cannot be 0.")
except IndexError:
    print("Index out of range.")
Index out of range.

If two errors need the same handling, list them together: except (ValueError, TypeError):. To see the message Python attached, add a name: except ValueError as e:, then print e.

else and finally

else runs only when the try block raised nothing, which keeps the code that depends on success out of the try block, so you don’t accidentally catch its errors too. finally runs every time, error or not, and is where clean-up goes.

def reciprocal(n):
    try:
        value = 1 / n
    except ZeroDivisionError:
        print("No reciprocal for 0.")
    else:
        print(f"1/{n} = {value}")
    finally:
        print("Checked", n)

reciprocal(4)
reciprocal(0)
1/4 = 0.25
Checked 4
No reciprocal for 0.
Checked 0

Raising your own errors

Sometimes the input is valid Python but wrong for your program. raise stops the function with a clear message, and the caller decides what to do.

def set_discount(percent):
    if not 0 <= percent <= 50:
        raise ValueError(f"discount must be between 0 and 50, got {percent}")
    return percent

try:
    set_discount(80)
except ValueError as e:
    print("Rejected:", e)
Rejected: discount must be between 0 and 50, got 80

Worked example: read settings without stopping at the first bad one

Settings usually arrive as text, from a file or a form, and some values are wrong. The function below converts each one, records a readable problem for each failure, and keeps the good values, so the caller gets the full list of problems in one go instead of fixing them one crash at a time.

raw_settings = {"timeout": "30", "retries": "three", "port": "8080", "ratio": "0"}

def parse_settings(raw):
    settings, errors = {}, []
    for key, text in raw.items():
        try:
            number = int(text)
            if key == "ratio":
                number = 100 / number
        except ValueError:
            errors.append(f"{key}: {text!r} is not a whole number")
        except ZeroDivisionError:
            errors.append(f"{key}: can't be 0")
        else:
            settings[key] = number
    return settings, errors

settings, errors = parse_settings(raw_settings)
print(settings)
for e in errors:
    print("Problem:", e)
{'timeout': 30, 'port': 8080}
Problem: retries: 'three' is not a whole number
Problem: ratio: can't be 0

Each except block matches one kind of failure and turns it into a message a person can act on. The else block stores the value only when the conversion worked. The same shape works for rows in a CSV file, records from an API or answers in a form: collect the problems, keep what’s valid, and report everything at the end.

Files that might not be there

Opening a file is the classic place for try and except, because whether the file exists is outside your program’s control. Catch only FileNotFoundError, and read the file in the else block, so an error while reading isn’t mistaken for a missing file:

def read_first_line(path):
    try:
        f = open(path, encoding="utf-8")
    except FileNotFoundError:
        return None
    else:
        with f:
            return f.readline().strip()

print(read_first_line("missing.txt"))
None

Returning None is one choice; logging a warning or raising a clearer error of your own are others. What matters is that the decision is deliberate.

Try it yourself

Write a function to_number(text) that returns the text as a float, or None when it can’t be converted. Then use it on ["3.5", "n/a", "12", ""].

def to_number(text):
    try:
        return float(text)
    except ValueError:
        return None

print([to_number(x) for x in ["3.5", "n/a", "12", ""]])
[3.5, None, 12.0, None]

Notice that the empty string fails too: float(“”) raises ValueError, which is often exactly the case real data throws at you.

Mistakes to avoid

  • Catching everything with a bare except, or except Exception: around a whole program. Catch what you expect, where you expect it.
  • Putting too much code in the try block. Keep it to the lines that can raise the error you’re handling.
  • Swallowing errors silently. If you catch an error, log or report it; an empty except block hides problems until they cost more.

Next in the series: reading and writing JSON, where these patterns help when a file is missing or malformed.

Want to go further?

I teach professionals one to one, and I build these systems for businesses. See Python AI mentoring or see what I build.