Module 25: Exception Handling Practice

Make your code robust! Learn to handle errors gracefully.

Anatomy of Error Handling

A `try...except` block helps catch errors. Click each highlighted part of the code below to see its role.

try: result = 10 / 0 # Potential error here except ZeroDivisionError: print("Cannot divide by zero!")

Identify all 7 parts!

What's the Outcome?

Look at the code. What will happen when it runs? Select the correct outcome below, then check your answer.

Error Proofing Challenge

The code below might crash! Modify it in the editor by adding a `try...except` block to handle the potential `ValueError` if the user enters text instead of a number. Print a friendly message in the `except` block.

Goal: Prevent crash from non-numeric input.
Result of check will appear here...

Match the Handler

Which `except` block is needed to correctly handle the potential error in the `try` block below? Click the right handler.

try:
some_code = ???
except WhichError:
print("Error handled!")

Mini Missions!

Apply your knowledge! Complete these coding tasks using `try...except`.

Mission 1: Safe Division

Write code that divides `100` by a variable `divisor` (assume it exists). Use `try...except` to catch a potential `ZeroDivisionError` and print "Cannot divide by zero." if it happens. Otherwise, print the result.

Mission 2: Robust Input

Ask the user for their age using `input()`. Convert it to an integer using `int()`. Use `try...except` to catch a `ValueError` if they enter non-numeric text, printing "Invalid input, please enter a number." If successful, print "Age accepted.".

Module 25 Practice Complete!

Excellent! You've practiced handling errors and making your code more robust.
Ready for more challenges? Try the Advanced Practice for Module 25!