✦ Python Foundations Working with Data module

Concept 22 · Error Handling

Handle expected errors.
Keep the program helpful.

Programs often receive values they cannot fully control. Error handling lets a program respond to an expected runtime problem instead of stopping immediately.

01 Learn02 Try03 Predict

Learning as a guest

Learning as a guest? Save your progress!

Create a free account to learn with Sloby AI, check your understanding, and track your progress.

The entire platform is free throughout 2026. Foundations stays free forever.

Handle an expected runtime problem, then continue the program.

You already know operations that can succeed or fail. int("42") works, while int("abc") cannot turn that text into an integer. Likewise, 10 / 2 works, but 10 / 0 causes a problem while the program runs. Use try and except when the program expects and knows how to handle a particular runtime problem.

value = "abc"

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

Python enters try and attempts int(value). Here int("abc") raises ValueError, so Python skips the remaining lines in that try block, finds the matching except ValueError, and runs its message. Code after the whole try/except structure can then continue.

Please enter a valid number.

Keep syntax errors separate from runtime exceptions. A syntax error means Python cannot read the written code correctly, such as print("Hello" with a missing parenthesis. An exception happens while syntactically valid code runs, such as int("abc"). try/except handles expected runtime exceptions; it does not repair invalid Python syntax.

↳

Use this error-handling mental model: risky operation → exception happens → matching except handles it → program continues

When no exception happens, except is skipped
value = "12"

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

print("Program continues.")

int("12") succeeds, so the rest of try runs and prints 12. No ValueError happens, so that except block is skipped. Python then reaches print("Program continues."). An except block does not run every time; it runs only when its matching exception happens.

ValueError: the value cannot be used that way
int("42")
int("abc")

Both inputs are strings, but "42" can become an integer and "abc" cannot. For this lesson, read ValueError as a useful signal that a value cannot be processed in the requested way.

ZeroDivisionError: a different problem needs a different handler
number = 10

try:
    print(number / 0)
except ZeroDivisionError:
    print("Cannot divide by zero.")

Dividing by zero raises ZeroDivisionError, not ValueError. Different expected problems have different exception types, so choose the handler that matches the operation you are protecting.

Two except branches describe two expected paths
value = "5"

try:
    number = int(value)
    print(10 / number)
except ValueError:
    print("Please enter a number.")
except ZeroDivisionError:
    print("Cannot divide by zero.")

With "5", conversion and division succeed, so neither handler runs. With "abc", conversion raises ValueError. With "0", conversion succeeds but division raises ZeroDivisionError. Python chooses the matching except branch for the problem that happened.

The rest of try is skipped after an exception
value = "0"

try:
    number = int(value)
    result = 10 / number
    print(result)
except ValueError:
    print("Invalid number.")
except ZeroDivisionError:
    print("Cannot divide by zero.")

print("Done.")

Trace it: int("0") returns 0, then 10 / 0 raises ZeroDivisionError. Python skips print(result), runs the matching handler, prints "Cannot divide by zero.", and then continues after the structure to print "Done.".

Catch errors you expect and know how to handle
except ValueError:
    print("Please enter a valid number.")

A specific handler documents what the program expects and how it will respond. Catching everything without knowing why can hide a different unexpected problem, so begin with the concrete errors your code can handle meaningfully.

A practical error-handling reading checklist

  1. Find the risky operationWhich operation in try might fail while it runs?
  2. Identify the expected exceptionWould this operation cause ValueError, ZeroDivisionError, or neither?
  3. Trace the try blockWhich lines run successfully before an exception, if one occurs?
  4. Find the matching exceptWhich except handler matches the exception that happened?
  5. Skip the rest of try after an exceptionAfter an exception, Python leaves the remaining statements in that try block.
  6. Continue after try/exceptWhat code runs next after a matching handler has finished, or after no exception happened?

Common beginner mistakes

  • Thinking except always runsAn except block runs only when its matching exception happens.
  • Expecting try/except to fix syntax errorsPython syntax must be valid before runtime error handling can run.
  • Catching the wrong exception typeValueError does not handle ZeroDivisionError; match the handler to the expected problem.
  • Expecting the next line inside try to run after an exceptionOnce an exception happens, Python skips the remaining statements in that try block.
  • Catching everything without knowing whyPrefer specific expected errors that the program can handle clearly.
  • Forgetting that execution can continue afterwardAfter a matching handler finishes, code after the try/except structure can still run.

Python Playground

Loading Python runtime…

Change value to "12", "abc", or another string and trace whether the try body succeeds or the ValueError handler runs.

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

Sign in to ask Sloby

Create a free account or sign in to get AI guidance while you learn.

Sign in to check your understanding

Create a free account or sign in to receive AI feedback and save your learning progress.

Python AI Tutor · Learn by understanding, not just by running code.