Errors and exceptions

Topic 1 of 4 in Errors and files7 min readBeginnerFree course

Overview

Things go wrong in every real program: users type letters where you expect numbers, files go missing, networks drop. When Python hits a problem it can’t continue from, it raises an exception. If nothing handles it, the program stops with a traceback. Exception handling lets you catch the problem, deal with it sensibly, and carry on.

What an exception looks like

Python
age = int("twenty")
Text
Traceback (most recent call last):
  File "app.py", line 1, in <module>
    age = int("twenty")
ValueError: invalid literal for int() with base 10: 'twenty'

The last line names the exception type (ValueError) and a message. Every exception is an object of a particular type.

try and except

Wrap the code that might fail in try, and say what to do if it does in except:

Python
text = input("Age: ")
try:
    age = int(text)
    print(f"Next year you'll be {age + 1}")
except ValueError:
    print("Please type a whole number.")
print("Program continues")
  • Python runs the try block.
  • If a ValueError happens, it jumps straight to the except block — the rest of the try block is skipped.
  • If no error happens, the except block is skipped.
  • Either way, the program carries on after the whole statement.

Combined with a loop, this gives robust input:

Python
while True:
    try:
        age = int(input("Age: "))
        break
    except ValueError:
        print("Please type a whole number.")

Common exceptions

Common built-in exceptions. BaseException is at the top, with KeyboardInterrupt and Exception below it. Under Exception: ValueError — a bad value, like int(“abc”); TypeError — the wrong type, like “a” + 1; KeyError — a missing dict key; IndexError — a list index too big; ZeroDivisionError — 1 / 0; FileNotFoundError — opening a missing file; NameError — a name not defined; AttributeError — no such attribute. except Exception catches all of these — but catch the specific error you expect whenever you can.

Exceptions form a family tree. except Exception would catch every error in the diagram — which sounds convenient, but it’s dangerous: it also hides bugs you didn’t expect, like a misspelled variable name. Catch the specific errors you expect and let real bugs show themselves.

Catching several exceptions

Several except blocks handle different problems differently; Python uses the first that matches:

Python
try:
    result = int(a) / int(b)
except ValueError:
    print("Not a number")
except ZeroDivisionError:
    print("Cannot divide by zero")

To handle several types the same way, use a tuple:

Python
except (KeyError, IndexError):
    print("Not found")

Using the exception object

as name gives you the exception itself, with its message:

Python
try:
    price = prices["pie"]
except KeyError as error:
    print("Missing key:", error)       # Missing key: 'pie'

else and finally

The full form has two more optional parts:

try / except / else / finally. try: n = int(text) runs the risky code. except ValueError: print(“Not a number”) runs only if it failed. else: print(“Got”, n) runs only if it worked. finally: print(“Done”) always runs — clean up here. With text = “42” the output is Got 42, Done; with text = “abc” it is Not a number, Done.

  • else runs only if the try block succeeded. Put the “everything worked” code here rather than in the try block, so the try contains only the line that can fail — then you won’t accidentally catch errors from other lines.
  • finally runs no matter what — success, handled error, unhandled error, even return or break. Use it for clean-up such as closing connections.
Python
try:
    n = int(text)
except ValueError:
    print("Not a number")
else:
    print("Got", n)
finally:
    print("Done")

(For files, the with statement does the clean-up for you — see Reading and writing files.)

Keep try blocks small

Python
# Too broad: which line raised the ValueError?
try:
    age = int(input("Age: "))
    height = float(input("Height: "))
    bmi = weight / height ** 2
    ...
except ValueError:
    print("Bad input")

Wrap only the lines that can raise the error you’re handling. Small try blocks make it obvious what can go wrong and where.

Don’t silence errors

The worst pattern is catching everything and doing nothing:

Python
try:
    process(data)
except:            # bare except — catches EVERYTHING, even Ctrl+C
    pass           # and hides it

The program carries on as if nothing happened, with wrong data, and you have no idea why. If you catch an error, handle it: show a message, use a default, retry, or log it. Never use a bare except:.

Asking forgiveness vs looking before you leap

Two styles exist:

Python
# Look before you leap (LBYL)
if key in prices:
    price = prices[key]

# Easier to ask forgiveness than permission (EAFP)
try:
    price = prices[key]
except KeyError:
    price = 0

Python code often prefers the second style — especially for things you can’t check reliably in advance, like whether a file can be opened or whether text is a valid number. For simple cases, prices.get(key, 0) is better than either.

Rules: catch specific exceptions, keep try blocks small, put success code in else, clean-up in finally — and never silence errors with a bare except: pass.

Exercise

A calculator that never crashes

Write a loop that asks for two numbers and an operator (+, -, *, /) and prints the result. Use try/except so that: invalid numbers print Not a number: <text> and ask again; dividing by zero prints Cannot divide by zero; an unknown operator prints Unknown operator. Use else to print the result only when nothing went wrong. Typing q as the first number quits with Bye.

Python
while True:
    first = input("First number (q to quit): ")
    if first == "q":
        print("Bye")
        break
    second = input("Second number: ")
    op = input("Operator: ")
    # Convert, calculate and handle errors

Summary

  • An exception is Python’s way of signalling an error; unhandled, it stops the program with a traceback.
  • try: runs risky code; except SomeError: runs only if that error happens, and the program continues.
  • Catch specific exceptions (ValueError, KeyError, FileNotFoundError…), not everything.
  • else runs only when the try block succeeded; finally always runs — use it for clean-up.
  • except ValueError as error: gives you the exception object, with its message.