Skip to content

Handling Errors (try / except)

Programming Python Difficulty 1/5

Beginning of the lesson

Handling Errors (try / except)

How to keep your program calm when something goes wrong

Big Idea: Sometimes a program hits a problem it cannot handle — like dividing by zero, or turning the word "cat" into a number. Normally the program crashes and stops. With try / except you can catch that problem and let your program keep going, showing a friendly message instead of an ugly error.
By the end you will be able to:
  • explain what an exception (a runtime error) is,
  • write a try / except block to catch an error,
  • catch the right error, like ValueError or ZeroDivisionError,
  • make a program that fails gracefully instead of crashing.

1. What is an exception?

An exception is an error that happens while your program is running. Python notices that it cannot do what you asked, so it stops and prints an error message called a traceback.

Here is a tiny program with no protection. If the person types something that is not a whole number, it breaks:

number = int(input("Enter a number: "))
print("Double is", number * 2)

If the person types cat instead of a number, Python crashes with this traceback:

Traceback (most recent call last):
  File "program.py", line 1, in <module>
    number = int(input("Enter a number: "))
ValueError: invalid literal for int() with base 10: 'cat'

The last line, ValueError, is the name of the exception. Every kind of error has a name. Once you know the name, you can catch it.

2. The analogy: a safety net

Think of a tightrope walker high in the air. Most of the time they walk across just fine. But if they slip, a safety net catches them so they are not hurt — the show goes on.

try is you walking the rope. except is the safety net below. If nothing goes wrong, the net is never used. But if you slip (an error happens), the net catches you and your program keeps running instead of crashing to the ground.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers