Lab Activity: Practice Error Handling and Debugging
Objectives
-
Learn how to use
try/exceptfor handling errors. -
Create a custom exception (
NegativeNumberError). -
Build a simple input loop that only accepts positive integers.
-
Show friendly error messages when input is wrong.
-
Practice debugging with
breakpoint(). -
(Optional) Use logging to track invalid inputs.
Step 1 — Create Your File
Create a new file called app.py.
Step 2 — Custom Exception
Add a custom exception for negative numbers:
# app.py
class NegativeNumberError(Exception):
"""Raised when the user enters a negative number."""
pass
Step 3 — Input Loop with try/except
Write a loop that keeps asking for a number until the user enters a valid one:
while True:
try:
raw = input("Enter a positive integer: ")
number = int(raw) # may raise ValueError
if number < 0:
# our custom exception
raise NegativeNumberError()
if number == 0:
print("Zero is not allowed, please enter a number greater than zero.")
continue
# Valid input
print(f"Great, you entered {number}. Its square is {number * number}.")
break # exit the loop
except ValueError:
print("That's not a valid number, please try again.")
except NegativeNumberError:
print("Please enter a positive number, negative is not allowed.")
Step 4 — Test Your Program
Run it several times with these inputs:
-
hello→ “That’s not a valid number…” -
12.3→ “That’s not a valid number…” -
-5→ “Please enter a positive number…” -
0→ “Zero is not allowed…” -
7→ “Great, you entered 7. Its square is 49.”
Step 5 — (Optional) Add Logging
At the very top of your file:
import logging
logging.basicConfig(filename="errors.log", level=logging.WARNING)
Inside the except blocks, add:
logging.warning("Invalid input: %s", raw)
Now invalid attempts are saved to errors.log.
Outcome
By the end of this lab you’ll know how to:
-
Handle bad input with
try/except. -
Use a custom exception for special error cases.
-
Write clear messages for users.
-
Debug your code with
breakpoint(). -
(Optionally) log errors for later review.
