BeginnerLesson firstCategory 14 of 20

Error Handling (try/except)

Catch and handle runtime exceptions gracefully. Read the lesson first, then move through the exercises in order.

4 Sections5 Exercises

After reading

Practice Arena

Begin with the first exercise, then continue step by step through the module.

Start with ZeroDivisionError

Study Material

Read the full lesson

When things go horribly wrong

Imagine you build a calculator app. A user types in 10 / 0.

Math tells us you cannot divide by zero. Python aggressively agrees. If you run that code, Python panics, throws a ZeroDivisionError, and completely crashes your entire program.

Letting your app crash every time a user makes a mistake is terrible design. Instead, you need to catch these errors gracefully.

Putting code in a try block

You can protect risky code by wrapping it inside a try block.

python
print("Starting calculation...") try: result = 10 / 0 print(f"The result is {result}") except ZeroDivisionError: print("Error: You cannot divide by zero!") print("Program finished.")

Here is what happens:

  1. Python enters the try block and attempts 10 / 0.
  2. Python realizes this is illegal and immediately stops. It does not run the next print statement inside the try block.
  3. Instead of crashing, Python leaps into the except block and prints our error message safely.
  4. The program continues running normally and prints "Program finished."

Catching generic errors

Sometimes you don't know exactly what error will occur. Maybe the user typed letters instead of numbers, triggering a ValueError. Maybe a file was missing, causing a FileNotFoundError.

You can use a bare except Exception as e: to catch absolutely anything that goes wrong.

python
try: number = int("hello") except Exception as e: print(f"Something broke! The system said: {e}")

This will print: Something broke! The system said: invalid literal for int() with base 10: 'hello'.

💡 Best Practice: It is generally better to catch specific errors (like ZeroDivisionError) when you know they might happen. Catching generic exceptions should only be used as a final safety net.

What this lesson should give you

After this lesson, you should understand how to:

  • anticipate crashes caused by invalid data
  • wrap dangerous code in a try block
  • provide fallback behavior using except
  • capture the exact error message using as e

Interactive

Exercises for this topic

These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.