0Pricing
Python Academy · Lesson

Understanding Exceptions

Learn what exceptions are and how Python raises them.

Understanding Exceptions is a free Python Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Introduction

Exceptions are Python's mechanism for signalling and handling errors at runtime.

What is an Exception?

An exception is an event that disrupts normal program flow. Python raises exceptions when errors occur — e.g., dividing by zero.
# 1 / 0  # raises ZeroDivisionError
print('exceptions demo')

Exception Hierarchy

All exceptions inherit from BaseException. Most user-facing ones inherit from Exception. Specific types: ValueError, TypeError, KeyError, etc.
print(issubclass(ValueError, Exception))
print(issubclass(Exception, BaseException))

Common Built-in Exceptions

TypeError: wrong type. ValueError: right type, wrong value. KeyError: dict key missing. IndexError: list index out of range. AttributeError: no such attribute.
# Examples:
# int('abc')       -> ValueError
# d['missing']     -> KeyError
# [1,2][9]         -> IndexError
print('common exceptions')

The Traceback

When an exception is unhandled, Python prints a traceback: the call stack from bottom (most recent) to top. Learn to read it.
def f(): return 1/0
# f()  # shows traceback
print('traceback demo')

Exception Object

Each exception carries a message. str(e) or e.args gives the description. Access inside except as: except ValueError as e.
try:
    int('abc')
except ValueError as e:
    print(type(e).__name__, e)

Catching Multiple Types

except (TypeError, ValueError): catches either type in one clause.
def parse(x):
    try:
        return int(x)
    except (TypeError, ValueError):
        return None
print(parse('abc'), parse(None))

The Exception Group (3.11+)

Python 3.11 adds ExceptionGroup for multiple simultaneous exceptions, handled with except* syntax.
# Python 3.11+:
# try: ...
# except* ValueError as eg:
#     print(eg.exceptions)
print('exception group demo')

Warnings vs Exceptions

import warnings; warnings.warn('msg') issues a warning without raising. Use for deprecations and soft errors.
import warnings
warnings.warn('This is deprecated', DeprecationWarning)
print('warning issued')

sys.exc_info()

Inside an except block, sys.exc_info() returns (type, value, traceback) — useful for logging full exception details.
import sys
try:
    1/0
except:
    exc_type, exc_val, _ = sys.exc_info()
    print(exc_type, exc_val)

Exception Chaining

raise NewError('msg') from original_exc chains exceptions. The __cause__ attribute links them.
try:
    int('abc')
except ValueError as e:
    raise RuntimeError('parse failed') from e

Quick Check

Which exception is raised when you access a dict with a key that does not exist?

Recap

Exceptions inherit from BaseException. Read tracebacks bottom-up. Catch with except as e. Common types: ValueError, TypeError, KeyError, IndexError, AttributeError.

Keep Going

Great work! Move on to the next lesson to keep progressing.

Frequently asked questions

Is the “Understanding Exceptions” lesson free?

Yes — the full text of “Understanding Exceptions” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Understanding Exceptions”?

Learn what exceptions are and how Python raises them. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Understanding Exceptions” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Understanding Exceptions
  2. try / except / else / finally
  3. Raising and Re-raising Exceptions
  4. Custom Exception Classes
← Back to Python Academy