SyntaxPilot
Courses/Python/Lesson 18

Python · Lesson 18 of 40 · 11 min

Errors and exceptions

queued

These are the notes for Python episode 18. In seventeen episodes we've seen plenty of red error messages, and every one of them stopped the program on the spot. In this episode a chai stall's billing app crashes because a customer typed the word "two", checking every input in advance turns out not to work, and we invent exception handling: try the risky code, and have a plan B. You will learn what an exception is, try and except, why a bare except: hides your own bugs, catching specific exceptions and as e, several except blocks, how to read a traceback, the exceptions you'll meet most, else and finally, and raise for your own errors. Every example below runs as-is in the SyntaxPilot compiler, with its real output from Python 3.13. Programs that read input show the input that was typed in the compiler's input box.

The problem: the customer typed "two"

A chai stall has a small billing app. It asks "How many chai?", and with 2 it says Total: 30. But real customers type all sorts of things. One types the word two:

price = 15
qty = int(input("How many chai? "))
print("Total:", price * qty)
print("Thank you!")

Input: two. Output:

How many chai? Traceback (most recent call last):
  File "main.py", line 2, in <module>
    qty = int(input("How many chai? "))
ValueError: invalid literal for int() with base 10: 'two'

Thank you! never printed. The program stopped at line 2, and the next customer waits while someone restarts it.

An exception is an error that happens while the program runs (as opposed to a SyntaxError, which Python finds before running anything). When an exception happens and nobody handles it, Python stops the whole program and prints a report called a traceback.

The obvious fix: check everything first

Strings have isdigit(): True if every character is a digit. So check before converting:

price = input("Price: ")

if price.isdigit():
    print("Price saved:", float(price))
else:
    print("Not a number!")

Input: 12.5. Output:

Price: Not a number!

A perfectly good price was rejected, because . isn't a digit. We could add a rule for the dot, then minus signs, then spaces, then 1e3...

Why it fails: you can't predict every valid and invalid way of typing a number. But int() and float() already know all the rules. So don't check first: try it, and have a plan B if it fails. (Programmers call this "it's easier to ask forgiveness than permission".)

try and except

At the chai stall In Python
Try the card payment; most days it works try: the normal plan, the code that might fail
Card declined? Take cash; the shop stays open except ValueError: plan B, runs only if that error happens
Next customer; the queue keeps moving the program continues after the block
price = 15
try:
    qty = int(input("How many chai? "))
    print("Total:", price * qty)
except ValueError:
    print("Please type a number, like 2")
print("Thank you!")

Input: two. Output:

How many chai? Please type a number, like 2
Thank you!

Input: 3. Output:

How many chai? Total: 45
Thank you!

How it runs:

  1. Python runs the lines inside try one by one.
  2. If no error happens, the except block is skipped.
  3. If an error happens, Python jumps straight to the matching except, skipping the rest of the try block. (Total: was never printed for two.)
  4. Either way, the program continues after the whole block.

Another example of the jump:

try:
    print("A")
    x = [1, 2][5]
    print("B")
except IndexError:
    print("C")
print("D")

Output:

A
C
D

B is skipped: the error on the line before it sent Python to except.

The bare except: trap

except: with no name catches every error. It's tempting, but watch what happens when we make a typo (prise instead of price) and the customer types a good number, 2:

price = 15
try:
    qty = int(input("How many chai? "))
    print("Total:", prise * qty)
except:
    print("Please type a number, like 2")

Input: 2. Output:

How many chai? Please type a number, like 2

The customer did type a number. The real problem is our typo, a NameError, but the bare except caught it and blamed the customer. A bug in our own code is now hidden, and could take hours to find.

The fix: catch only the exception you expect. as e gives the exception a name, so you can print its message:

price = 15
try:
    qty = int(input("How many chai? "))
    print("Total:", prise * qty)
except ValueError as e:
    print("Please type a number:", e)

Input: 2. Output:

How many chai? Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print("Total:", prise * qty)
                    ^^^^^
NameError: name 'prise' is not defined. Did you mean: 'price'?

Now the typo shows up loudly, and Python even suggests the fix. Catch what you expect, and let real bugs crash. With input two, the same program prints Please type a number: invalid literal for int() with base 10: 'two'.

except Exception as e: catches almost everything too. Use it only at the very top of a program, to log an unexpected error, never to silence one.

Several except blocks

Splitting a ₹600 bill among friends. Two things can go wrong: not a number, or zero friends.

bill = 600
try:
    friends = int(input("How many friends? "))
    print("Each pays:", bill / friends)
except ValueError:
    print("Type a whole number")
except ZeroDivisionError:
    print("At least one person has to pay!")
Input Output
0 How many friends? At least one person has to pay!
x How many friends? Type a whole number
4 How many friends? Each pays: 150.0

Python checks the except blocks from top to bottom and runs the first one that matches. One block can also catch several types, with a tuple:

try:
    print(int("12abc"))
except (ValueError, TypeError) as e:
    print(type(e).__name__, "->", e)

Output:

ValueError -> invalid literal for int() with base 10: '12abc'

type(e).__name__ gives the exception's type as text.

Reading a traceback

  1. Read the last line first: the exception type and its message.
  2. Then the line just above it: the file and line number, and the code on that line.
  3. Higher lines show the chain of function calls that led there (the outermost call at the top).
menu = {"chai": 15, "samosa": 20}
orders = ["chai", "samosa"]

print(menu["coffee"])

Output:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print(menu["coffee"])
          ~~~~^^^^^^^^^^
KeyError: 'coffee'

Bottom line: a KeyError, the missing key is 'coffee'. Just above: line 4. Two fixes:

menu = {"chai": 15, "samosa": 20}
item = "coffee"
try:
    print(item, "costs", menu[item])
except KeyError:
    print("Sorry, no", item, "today")
print(menu.get("coffee", "not on the menu"))

Output:

Sorry, no coffee today
not on the menu

The exceptions you'll meet most

Exception When Real example message
ValueError the right type but a wrong value invalid literal for int() with base 10: 'two'
TypeError the wrong type for an operation can only concatenate str (not "int") to str
NameError a name that doesn't exist (often a typo) name 'prise' is not defined. Did you mean: 'price'?
KeyError a dictionary key that isn't there 'coffee'
IndexError a list position that doesn't exist list index out of range
ZeroDivisionError dividing by zero division by zero
FileNotFoundError opening a file that doesn't exist (episode 20) [Errno 2] No such file or directory: 'marks.txt'
RecursionError too many nested calls (episode 15) maximum recursion depth exceeded

Exceptions form a family tree: ZeroDivisionError is a kind of ArithmeticError, which is a kind of Exception. except ArithmeticError: would also catch a ZeroDivisionError. You'll see how such trees are built with classes in episode 22.

try:
    x = 10 / 0
except Exception as e:
    print("Caught:", type(e).__name__)

Output:

Caught: ZeroDivisionError

else and finally

Block Runs when Chai stall
try always first take the order
except only when the try failed (with that error) the order was wrong
else only when the try did not fail place the order
finally always, error or not pull the shutter down at night
try:
    qty = int(input("How many? "))
except ValueError:
    print("Not a number")
else:
    print("Order placed for", qty)
finally:
    print("Shutter closed")
Input Output
3 How many? Order placed for 3 then Shutter closed
z How many? Not a number then Shutter closed
  • else keeps the try block short: only the risky line goes in try, so you don't accidentally catch errors from the other lines.
  • finally is for clean-up that must happen no matter what: closing a file, a network connection, a database. It runs even when the try block returns:
def f():
    try:
        return "from try"
    finally:
        print("finally runs first")

print(f())

Output:

finally runs first
from try

Keep the try block small

  • Don't wrap twenty lines in one try: when something fails you won't know which line it was, and an unrelated bug can land in the wrong except.
  • Put only the risky line in try, what should happen when it worked in else, and clean-up that must always happen in finally.

raise: your own errors

So far Python raised the errors. You can raise your own with raise:

def withdraw(balance, amount):
    if amount > balance:
        raise ValueError("Insufficient balance")
    return balance - amount

print(withdraw(1000, 300))
print(withdraw(1000, 5000))

Output:

700
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    print(withdraw(1000, 5000))
          ~~~~~~~~^^^^^^^^^^^^
  File "main.py", line 3, in withdraw
    raise ValueError("Insufficient balance")
ValueError: Insufficient balance

Read it bottom-up: the error was raised at line 3, inside withdraw, which was called from line 7.

Why raise instead of print? The function can't know what the app should do: show a message, offer a smaller amount, or write to a log. raise reports the problem; the caller decides:

def withdraw(balance, amount):
    if amount > balance:
        raise ValueError("Insufficient balance")
    return balance - amount

try:
    print(withdraw(1000, 5000))
except ValueError as e:
    print("ATM says:", e)

Output:

ATM says: Insufficient balance

Pick the exception type that fits: ValueError for a bad value, TypeError for a wrong type. Your own exception types come once we learn classes (episode 21).

Common mistakes

Mistake What you see Why Fix
int(input()) when the user types two ValueError: invalid literal for int() with base 10: 'two' nobody handled the exception try: ... except ValueError:
price.isdigit() before float() no error, 12.5 rejected you can't predict every format try: float(price) and catch ValueError
a bare except: no error, a NameError is hidden and the user is blamed it catches your own bugs too except ValueError:
bill / friends with 0 ZeroDivisionError: division by zero dividing by zero except ZeroDivisionError: or check first
menu["coffee"] KeyError: 'coffee' the key isn't in the dict if "coffee" in menu, menu.get(), or except KeyError:
"Total: " + 45 TypeError: can only concatenate str (not "int") to str text and a number can't be added "Total: " + str(45) or an f-string
too many lines inside try the wrong except runs for an unrelated error the block catches more than intended keep only the risky line in try; the rest in else
print instead of raise in a function the caller carries on with a wrong value the problem isn't reported raise ValueError("...")

Mini project: a bill splitter that never crashes

while True keeps asking. try reads the number and divides. On an error, explain what's wrong and loop again. else (nothing failed) breaks out of the loop.

# Mini project: split the bill, never crash
bill = 600
while True:
    try:
        friends = int(input("How many friends? "))
        share = bill / friends
    except ValueError:
        print("  Type a whole number")
    except ZeroDivisionError:
        print("  Can't split between 0 people")
    else:
        break
print("Each pays:", round(share, 2))

Input (three lines): two, 0, 4. Output:

How many friends?   Type a whole number
How many friends?   Can't split between 0 people
How many friends? Each pays: 150.0

Three tries, zero crashes.

Extend it: raise a ValueError if there are more than 20 friends, and catch it in the same loop.

Practice

1. Ask for an age until it's a valid whole number.

Solution
while True:
    try:
        age = int(input("Your age: "))
        break
    except ValueError:
        print("  Please type a whole number")
print("You are", age)

Input: abc, -2x, 21. Output:

Your age:   Please type a whole number
Your age:   Please type a whole number
Your age: You are 21

2. safe_divide(a, b) that returns None on division by zero.

Solution
def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return None

print(safe_divide(10, 4))
print(safe_divide(10, 0))

Output:

2.5
None

3. Look up a menu item; handle the KeyError.

Solution
menu = {"chai": 15, "samosa": 20}
item = "coffee"
try:
    print(item, "costs", menu[item])
except KeyError:
    print("Sorry, no", item, "today")

Output:

Sorry, no coffee today

4. raise a ValueError for a negative or zero deposit, and catch it.

Solution
def deposit(balance, amount):
    if amount <= 0:
        raise ValueError("Deposit must be positive")
    return balance + amount

print(deposit(500, 200))
try:
    deposit(500, -50)
except ValueError as e:
    print("Error:", e)

Output:

700
Error: Deposit must be positive

Quick quiz

1. The video's quiz:

try:
    x = int("5") / 0
except ValueError:
    print("A")
except ZeroDivisionError:
    print("B")
finally:
    print("C")
Answer

B then C. int("5") works, so there's no ValueError. Dividing by zero raises ZeroDivisionError, which prints B, and finally always runs: C.

2. What does this print?

try:
    qty = int("3")
except ValueError:
    print("bad")
else:
    print("else", qty)
finally:
    print("done")
Answer
else 3
done

No error, so except is skipped, else runs, and finally always runs.

3. Why is except: (with no name) dangerous?

Answer

It catches every exception, including NameErrors and TypeErrors caused by bugs in your own code, so the bug is hidden behind a misleading message.

4. In a traceback, which line do you read first?

Answer

The last line: the exception type and message. Then the line above it for the file and line number.

Interview questions

  1. What is an exception? An error detected while the program runs; if not handled, it stops the program and prints a traceback.
  2. Syntax error vs exception? A SyntaxError is found before the program runs (the code isn't valid Python); an exception happens at run time in valid code.
  3. Explain try/except/else/finally. try holds risky code; except runs if a matching exception is raised; else runs if no exception was raised; finally always runs, for clean-up.
  4. Why avoid a bare except:? It catches everything, including bugs and even KeyboardInterrupt, hiding real problems. Catch specific exceptions.
  5. What does raise do? Raises an exception explicitly, e.g. raise ValueError("Insufficient balance"), so the caller can decide how to handle it.
  6. How do you catch several exception types in one block? except (ValueError, TypeError) as e:.
  7. Does finally run if the try block returns? Yes, finally runs before the function actually returns.
  8. What is EAFP vs LBYL? "Easier to ask forgiveness than permission" (try it and handle the exception) vs "look before you leap" (check first). Python style usually prefers EAFP.

Glossary

Term Meaning Example
Exception An error that happens while the program runs ValueError
Raise To signal an exception (Python does it, or you do with raise) raise ValueError("...")
Handle / catch To deal with an exception so the program continues except ValueError:
Unhandled exception An exception nobody catches; it stops the program the two crash
try The block holding code that might fail try: qty = int(...)
except Plan B: runs when a matching exception happens in try except ZeroDivisionError:
Bare except except: with no type; catches everything (avoid) except:
as e Gives the caught exception a name, to read its message except ValueError as e:
else (try) Runs only when the try block raised nothing else: print("Order placed")
finally Always runs, error or not; used for clean-up finally: print("Shutter closed")
Traceback Python's error report: the call chain, line numbers and the error Traceback (most recent call last):
ValueError Right type, wrong value int("two")
TypeError Wrong type for an operation "Total: " + 45
NameError A name that isn't defined prise
KeyError A missing dictionary key menu["coffee"]
IndexError A list position that doesn't exist [1, 2][5]
ZeroDivisionError Division by zero 600 / 0
FileNotFoundError A file that doesn't exist (episode 20) open("marks.txt")
Exception The parent of almost all exceptions except Exception as e:
isdigit() True if every character is a digit "12".isdigit() → True
menu.get(key, default) Looks up a key without a KeyError menu.get("coffee", 0)
EAFP "Easier to ask forgiveness than permission": try, then handle try: float(price)

Summary

  • An exception is a run-time error; unhandled, it stops the program and prints a traceback.
  • Checking every input yourself doesn't work (a valid 12.5 was rejected). Try it, and handle the failure.
  • try: holds the risky code; except SomeError: is plan B; then the program carries on.
  • Catch specific exceptions; a bare except: hides your own bugs. as e gives you the message.
  • Several except blocks handle different errors; Python runs the first that matches.
  • Read tracebacks bottom-up: the error, then where.
  • else runs when nothing failed; finally always runs.
  • raise reports a problem; the caller decides what to do.

Next episode: modules and packages. How to split a program into files, import them, and use the huge library of tools that comes free with Python.