Python Exception Handling

Let’s look at exception handling

  1. Notice

    A try block holds the operation that may fail. except handles matching errors; finally runs whether or not an error occurred.

  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
number = 3
try:
    print(12 / number)
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("finished")
Live state

Top-level scope

number→Object 1
Object 1 · int3
This step

A try block holds the operation that may fail. except handles matching errors; finally runs whether or not an error occurred.

Follow success and failure

Handle the failure you expect. A finally block provides cleanup as control leaves the try statement.

Image brief

Alt text
An operation in try can succeed or raise an exception handled by a matching except block; finally runs when leaving either path.
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python Exception Handling". Teaching focus: Handle the failure you expect. A finally block provides cleanup as control leaves the try statement. Depict exactly the relationships and labels in this reference diagram: TRY THE OPERATION / \ succeeds raises matching exception | | continue except handler \ / finally block 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: An operation in try can succeed or raise an exception handled by a matching except block; finally runs when leaving either path.

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
number = 3
try:
    print(12 / number)
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("finished")
Live state

Top-level scope

number→Object 1
Object 1 · int3
This step

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

Terminal
Output
4.0
finished

What do you expect this program to print?

What does this example display?

number = 3
try:
    print(12 / number)
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("finished")
What does this example display?
Choose one answer. You can try again.

Answer and explanation

4.0 finished

Follow the printed values in order. The output is: 4.0 finished

Which explanation matches what you learned?

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

Answer and explanation

A try block holds the operation that may fail. except handles matching errors; finally runs whether or not an error occurred.

A try block holds the operation that may fail. except handles matching errors; finally runs whether or not an error occurred.

A Little Recap on Exceptions

Sometimes, when your program runs, things can go wrong — like dividing a number by zero, or trying to open a file that doesn’t exist. These problems are called exceptions in Python.

What is an Exception?

An exception is a message that Python shows when something goes wrong while running your code. It stops the program unless you tell Python how to handle it.

Why Do Exceptions Exist?

Exceptions are helpful! They don’t crash your computer — they just let you know something unusual happened. If you don’t handle them, your program will stop. But if you do, your program can keep going or show a friendly message instead.

Example: A Simple Error

print(10 / 0)
ZeroDivisionError: division by zero

Why this happened: You’re trying to divide 10 by 0, which is not allowed in math. So Python shows a ZeroDivisionError.

How to Handle Exceptions

Python gives us a way to handle such situations using try and except blocks.

Example: Handling Division by Zero

try:
    print(10 / 0)
except ZeroDivisionError:
    print("Oops! You can't divide by zero.")
Oops! You can't divide by zero.

Why this works: The code inside try might cause an error. If it does, the code inside except runs instead of crashing the program.

Another Example: Converting Text to a Number

try:
    number = int("hello")
    print(number)
except ValueError:
    print("That’s not a number!")
That’s not a number!

Why: You’re trying to turn the word "hello" into a number. That’s not possible, so Python gives a ValueError.

Using a General Except

try:
    print(10 / 0)
except:
    print("Some error happened!")

Note: You can use except alone, but it's better to catch specific errors like ZeroDivisionError or ValueError if you know what to expect.

Conclusion

Exceptions are normal in programming. They help you find and fix problems. Using try and except, you can write programs that don’t crash — even when something goes wrong.

=

What to remember

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

Remember

A try block holds the operation that may fail. except handles matching errors; finally runs whether or not an error occurred.

Watch out for this idea

finally runs only after an exception.

This is the misconception to avoid.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Python Custom Exceptions →