✦ Python Foundations Working with Data module

Concept 22 · Error Handling

Handle expected errors.
Keep the program helpful.

A syntax error stops Python before it runs. An exception happens while code runs. Catch a specific expected exception, such as ValueError or ZeroDivisionError, instead of using a broad except.

01 Learn02 Try03 Predict

try and except handle expected errors while a program runs.

A syntax error stops Python before it runs. An exception happens while code runs. Catch a specific expected exception, such as ValueError or ZeroDivisionError, instead of using a broad except.

value = "abc"

try:
    number = int(value)
    print(number)
except ValueError:
    print("Please enter a valid number.")

int("abc") raises ValueError, so Python skips the rest of try and runs the matching except block.

Please enter a valid number.

Change one value, then explain how the resulting data changes.

↳

Keep this in mind: Follow each data operation in order before predicting the result.

Try it
value = "abc"

try:
    number = int(value)
    print(number * 2)
except ValueError:
    print("Please enter a valid number.")
# Try changing value to "12"

Run the example, then change one value and observe the result.

Python Playground

Loading Python runtime…

Edit the example and run it in your browser.

error_handling.pyPython
OutputWaiting for Python
The browser runtime is loading. You can still edit the example code.

Pyodide runs Python in a browser Web Worker. It is stopped and restarted if code keeps running. Browser execution is not a complete security boundary; do not enter secrets or rely on it for untrusted code isolation.

What will this program print?

Read each data operation before choosing an answer.

number = 10

try:
    print(number / 0)
except ZeroDivisionError:
    print("Cannot divide by zero")
Choose the output
Sloby, the Python AI Tutor mascot

Your learning mentor

Ask Sloby about error handling

Describe what feels unclear and Sloby will guide your reasoning.

Hi! I'm Sloby. Let's trace try and except one branch at a time.

What will this program print, and when would each except block run? Explain why catching specific exceptions is useful.

value = "5"

try:
    number = int(value)
    print(10 / number)
except ValueError:
    print("Not a number")
except ZeroDivisionError:
    print("Cannot divide by zero")
Python AI Tutor · Learn by understanding, not just by running code.