Python Exceptions

Let’s look at exceptions

  1. Notice

    An exception interrupts normal execution when an operation cannot finish. Catch an expected exception to choose a recovery path.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
text = '12'
try:
    number = int(text)
    print(number)
except ValueError:
    print("Please enter a whole number")
Live state

Top-level scope

text→Object 1
number→Object 2
Object 1 · str'12'Object 2 · int12
This step

An exception interrupts normal execution when an operation cannot finish. Catch an expected exception to choose a recovery path.

Picture exceptions

An exception interrupts normal execution when an operation cannot finish. Catch an expected exception to choose a recovery path.

Image brief

Alt text
A diagram for Python Exceptions. Instructions: text = '12' try: number = int(text) print(number) except ValueError: print("Please enter a whole number"). Displayed result: 12. The final example bindings are text --> object 1 (str); number --> object 2 (int). object 1: '12'; object 2: 12
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python Exceptions". Teaching focus: An exception interrupts normal execution when an operation cannot finish. Catch an expected exception to choose a recovery path. Depict exactly the relationships and labels in this reference diagram: EXAMPLE INSTRUCTIONS text = '12' try: number = int(text) print(number) except ValueError: print("Please enter a whole number") | v DISPLAYED RESULT 12 FINAL BINDINGS text --> object 1 (str) number --> object 2 (int) object 1: '12' object 2: 12 Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: A diagram for Python Exceptions. Instructions: text = '12' try: number = int(text) print(number) except ValueError: print("Please enter a whole number"). Displayed result: 12. The final example bindings are text --> object 1 (str); number --> object 2 (int). object 1: '12'; object 2: 12

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
text = '12'
try:
    number = int(text)
    print(number)
except ValueError:
    print("Please enter a whole number")
Live state

Top-level scope

text→Object 1
number→Object 2
Object 1 · str'12'Object 2 · int12
This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
12

What do you expect this program to print?

What does this example display?

text = '12'
try:
    number = int(text)
    print(number)
except ValueError:
    print("Please enter a whole number")
What does this example display?
Choose one answer. You can try again.

Answer and explanation

12

Follow the printed values in order. The output is: 12

Which explanation matches what you learned?

Which explanation matches what you learned?
Choose one answer. You can try again.

Answer and explanation

An exception interrupts normal execution when an operation cannot finish. Catch an expected exception to choose a recovery path.

An exception interrupts normal execution when an operation cannot finish. Catch an expected exception to choose a recovery path.

What Are Python Exceptions?

In Python, an exception is an error that disrupts the normal flow of a program. When something goes wrong during execution—like dividing by zero or trying to access an index that doesn’t exist—Python stops and raises an exception.

Knowing how and why they occur is the first step in building resilient, bug-free Python applications. Later, you'll learn how to catch and handle them, but first, we must learn to recognize them.

When Does Python Raise an Exception?

Python raises an exception during runtime when it encounters an issue that it doesn’t know how to handle. This stops the execution of the program and displays an error message (also called a traceback).

Basic Example: Division by Zero

x = 5
y = 0
result = x / y
print(result)
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    result = x / y
ZeroDivisionError: division by zero

Python gives us a traceback—a report of where the error occurred. In this case, it tells us exactly which line failed and what kind of error it was: ZeroDivisionError.

Another Example: Accessing a Non-Existent Index

fruits = ["apple", "banana", "cherry"]
print(fruits[5])
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(fruits[5])
IndexError: list index out of range

Here, the list only has 3 elements, indexed 0 through 2. Trying to access index 5 raises an IndexError.

Common Built-in Exceptions in Python

ExceptionDescription
ZeroDivisionErrorRaised when dividing by zero
TypeErrorRaised when an operation is applied to an object of inappropriate type
NameErrorRaised when a variable is not defined
IndexErrorRaised when a sequence index is out of range
KeyErrorRaised when a dictionary key isn’t found
ValueErrorRaised when a function receives an argument of right type but inappropriate value
AttributeErrorRaised when an invalid attribute reference is made
ImportErrorRaised when a module or name cannot be found during import

Best Practices for Beginners

  • Don’t ignore exceptions; read and understand them.
  • Use print statements or debugging tools to inspect values before failure points.
  • Always know the type and shape of your data before using it.
  • Refer to the traceback line numbers to locate and fix errors quickly.

Summary

Python exceptions are runtime errors that occur when something goes wrong while executing your code. In the next section, we’ll explore how to catch and handle these exceptions using try and except.

What to remember

Connect what you noticed in the example with the idea below.

Remember

An exception interrupts normal execution when an operation cannot finish. Catch an expected exception to choose a recovery path.

Watch out for this idea

An exception is just a normal return value.

This is the misconception to avoid.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Python Exception Handling →