Error Handling (try/except)
Catch and handle runtime exceptions gracefully. Read the lesson first, then move through the exercises in order.
After reading
Practice Arena
Begin with the first exercise, then continue step by step through the module.
Start with ZeroDivisionErrorStudy 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.
pythonprint("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:
- Python enters the
tryblock and attempts10 / 0. - Python realizes this is illegal and immediately stops. It does not run the next print statement inside the
tryblock. - Instead of crashing, Python leaps into the
exceptblock and prints our error message safely. - 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.
pythontry: 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
tryblock - 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.
ZeroDivisionError
Write a try/except block to catch a division by zero error.
ValueError on Cast
Catch an error when attempting to cast an invalid string to an integer.
FileNotFoundError
Attempt to open a non-existent file and gracefully handle the resulting error.
Multiple Exceptions
Write a block with multiple exception handlers.
else & finally Blocks
Write a full try/except/else/finally sequence.