Skip to content
Codewilds

Lesson 30 of 34 · Errors & Pythonic Tools

Python Exceptions: try, except, else and finally

medium20 XP3 min read

Things go wrong in every real program: a user types letters where a number belongs, a file is missing, a list turns out to be empty. Python reports such problems by raising an exception. If nothing handles it, the program stops with a traceback — but with try and except you can catch the exception and recover gracefully.

Reading a traceback

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

Read tracebacks from the bottom up: the last line names the exception type (ValueError) and explains what happened; the lines above show where.

Common built-in exceptions

Exception Typical cause
ValueError right type, wrong value: int("abc")
TypeError wrong type: "a" + 1
KeyError missing dictionary key
IndexError list index out of range
ZeroDivisionError dividing by zero
AttributeError missing attribute or method: None.upper()
FileNotFoundError opening a file that doesn't exist

try and except

Put the code that might fail in a try block and the recovery code in an except block:

text = "twelve"
try:
    age = int(text)
except ValueError:
    age = 0
print(age)   # 0

If the try block succeeds, the except block is skipped. If a ValueError occurs, Python jumps straight to except — the rest of the try block never runs.

Catch specific exceptions

Name the exceptions you expect, use several except clauses for different reactions, and add as to access the exception object:

def lookup(prices, item, count):
    try:
        return prices[item] / count
    except KeyError:
        return f"{item} is not for sale"
    except ZeroDivisionError as error:
        return f"Bad count: {error}"


print(lookup({"rope": 6}, "rope", 0))   # Bad count: division by zero

A tuple catches several types with one clause: except (ValueError, TypeError):. Catching everything with except Exception: is occasionally right — at the top level of a program, or in a function whose whole job is to report failures — but in ordinary code it hides real bugs.

else and finally

A try statement can have two more blocks:

  • else runs only if the try block raised no exception — the place for code that should run on success but whose own errors you don't want to catch.
  • finally runs no matter what — success, handled exception, unhandled exception, even after a return. It's used for cleanup such as closing files or releasing locks.
def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Cannot divide by zero")
        return None
    else:
        print("Division worked")
        return result
    finally:
        print("Finished")


divide(6, 3)   # Division worked, Finished  -> returns 2.0
divide(6, 0)   # Cannot divide by zero, Finished  -> returns None

Ask forgiveness, not permission

Python developers often prefer to just try an operation and handle the failure (EAFP: "easier to ask forgiveness than permission") rather than check every condition in advance (LBYL: "look before you leap"). try: value = d[key] except KeyError: ... is as Pythonic as if key in d:. Choose whichever reads more clearly.

Common mistakes

  • A bare except: catches everything, including typos in your own code and the user pressing Ctrl+C. Always name the exception.
  • Silencing errors with except ValueError: pass makes bugs invisible. At least log or report what happened.
  • Too much code in try: keep only the line that can fail inside, so you don't accidentally catch errors from unrelated code.
  • Wrong order of except clauses: Python uses the first matching clause, so except Exception before except ValueError means the second never runs.

Assignment

Write three functions:

  1. safe_divide(a, b) returns a / b, or None when b is zero. Catch ZeroDivisionError — don't check b with an if.
  2. parse_int(text, default=0) returns int(text), or default when the text isn't a valid whole number (ValueError).
  3. run_safely(func, log) calls func() with no arguments and records what happens by appending strings to the list log:
    • append "start" before calling func;
    • if func raises any Exception, append "error: <ExceptionTypeName>" and return None;
    • otherwise append "success" (in an else block) and return func's result;
    • in every case, append "done" last (in a finally block).
safe_divide(10, 4)              # 2.5
parse_int("abc", default=-1)    # -1
log = []
run_safely(lambda: 1 / 0, log)  # None
log                             # ["start", "error: ZeroDivisionError", "done"]

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Errors and exceptions in other languages

Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.

Lesson last updated on .

Write code ↓
Python+20 XP

Lesson 30 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.