Skip to content

Module 12 · Exception Handling — topic 1 of 11

Exceptions

What exceptions are, what happens when one is raised, how they travel up the call stack, the exception class hierarchy, and why handling them makes programs robust.

Beginner 8 min read·Lesson 183 of 306 in Python Programming

Learning objectives

  • Explain what happens when an exception is raised
  • Describe how exceptions propagate through function calls
  • Read an exception's type, message and class hierarchy

Definition

An exception is an object that signals an error or unusual condition during execution. When an exception is raised, normal execution stops and Python looks for a matching handler; if none is found, the program ends with a traceback.

Introduction

Programs meet the unexpected: a user types letters where a number belongs, a file is missing, a network is down. Python reports these situations by raising exceptions, and your code decides what to do about them.

Why it matters

Without exception handling, one bad input crashes the whole program. With it, you can skip a bad record, ask again, retry or fail with a clear message.

Detailed explanation

When an operation can't continue — dividing by zero, converting 'abc' to int — Python creates an exception object and raises it.

Execution of the current block stops immediately. Python looks for an enclosing try statement with a matching except clause.

If the current function has no handler, the exception propagates to the caller, then to its caller, and so on up the call stack.

If nothing handles it, Python prints a traceback (the chain of calls that led to the error, plus the exception type and message) and the program stops.

Exceptions are ordinary objects of classes. All built-in errors derive from Exception, which derives from BaseException. The class hierarchy lets you catch broad or narrow groups of errors.

An exception carries information: its type (type(e).__name__), its message (str(e)) and its arguments (e.args).

Exceptions are for exceptional situations; normal control flow should use if statements and loops.

Syntax

Python
try:
risky_operation()
except SomeError as e:
handle(e)
# execution continues here
  • Raised exceptions stop the current block.
  • A matching except clause handles them.
  • Unhandled exceptions end the program with a traceback.

Code examples

Catching an exception

Python
print("start")
try:
result = 10 / 0
print("never printed")
except ZeroDivisionError as e:
print("caught:", type(e).__name__, "-", e)
print("program continues")
Output
start
caught: ZeroDivisionError - division by zero
program continues

Exceptions are objects

Python
e = ValueError("bad value")
print(type(e).__name__, e.args, isinstance(e, Exception))
print([c.__name__ for c in ZeroDivisionError.__mro__])
Output
ValueError ('bad value',) True
['ZeroDivisionError', 'ArithmeticError', 'Exception', 'BaseException', 'object']

More examples

Propagation through function calls

Python
def parse_age(text):
return int(text)
def load_user(record):
name, age = record.split(",")
return name, parse_age(age)
def load_all(records):
users = []
for r in records:
try:
users.append(load_user(r))
except ValueError as e:
print(f"skipped {r!r}: {e}")
return users
print(load_all(["Asha,30", "Ravi,abc", "Meera", "Kiran,25"]))
Output
skipped 'Ravi,abc': invalid literal for int() with base 10: 'abc'
skipped 'Meera': not enough values to unpack (expected 2, got 1)
[('Asha', 30), ('Kiran', 25)]

Step-by-step explanation

  • The ValueError for 'abc' is raised deep inside parse_age.
  • Neither parse_age nor load_user handles it, so it propagates up to load_all.
  • load_all catches it, reports the bad record and moves on to the next one.

Expected output

Running “Propagation through function calls” prints exactly:

TextOutput
skipped 'Ravi,abc': invalid literal for int() with base 10: 'abc'
skipped 'Meera': not enough values to unpack (expected 2, got 1)
[('Asha', 30), ('Kiran', 25)]

Practical applications

  • Web servers catch exceptions per request so one bad request doesn't stop the server.
  • Data pipelines skip and log malformed rows.

Best practices

  • Handle exceptions where you can actually do something useful.
  • Let unexpected errors propagate rather than hiding them.
  • Read tracebacks from the bottom up.

Common mistakes

Ignoring the traceback

Avoid

# 'it crashed' — and the message is never read

Prefer

Read the last line (type and message) first, then follow the stack upwards.

The traceback tells you exactly what failed and where.

Important notes

  • KeyboardInterrupt and SystemExit derive from BaseException but not Exception, so except Exception doesn't catch Ctrl+C.

Key takeaways

  • Exceptions signal errors at runtime.
  • They propagate up the call stack until handled.
  • Unhandled exceptions stop the program with a traceback.

Try it yourself

  1. 1
    Write a function that averages a list of strings, skipping entries that aren't numbers.
  2. 2
    Print the __mro__ of FileNotFoundError and KeyError.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions cover the “Exception Handling” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this module