Activity: The "Bug Bounty" Challenge
Duration: 60 Minutes | Topic: Python Error Handling and Debugging
This activity transitions you from a "coder" to a "detective." You will take a broken, fragile script
and transform it into a robust, crash-proof program.
Phase 1: The "Crime Scene" (10 Minutes)
Your goal is to build a simple Division Calculator. However, the starter code below is riddled
with logic errors and lacks any protection against user input mistakes.
The Broken Code:
Python
def calculate_division():
num1 = input("Enter the first number: ")
num2 = input("Enter the second number: ")
# Logic Error: Can you spot why this won't work even with numbers?
result = num1 / num2
print("The result is: " + result)
calculate_division()
1. Run the code. Observe the TypeError.
2. Input "10" and "0". Observe the ZeroDivisionError (once the type error is fixed).
3. Input "hello" and "5". Observe the ValueError.
Phase 2: Building the Shield (20 Minutes)
Now, let's use try-except blocks to handle these crashes gracefully.
Your Task: Modify the script to catch specific errors. Follow the structure of the exception
hierarchy:
Updated Instructions:
1. Wrap the logic in a try block.
2. Add an except ValueError to catch non-numeric inputs.
3. Add an except ZeroDivisionError to prevent the universe from imploding when dividing by
zero.
4. Use a finally block to print a "Cleanup" message (e.g., "Calculation attempt finished").
Phase 3: Advanced Defense & Logging (20 Minutes)
A professional program doesn't just catch errors; it prevents them and logs what happened.
The Code Challenge:
Python
import logging
# Configure logging to see the "trail" of errors
[Link](level=[Link])
def advanced_calculator():
while True:
try:
x = float(input("\nEnter numerator: "))
y = float(input("Enter denominator: "))
if x > 1000000:
# Raise a custom error if the number is too big for our "tiny" calculator
raise ValueError("Number too large!")
result = x / y
except ValueError as e:
print(f"Input Error: {e}")
[Link]("Invalid input provided.")
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
else:
# This runs ONLY if no errors occurred
print(f"Success! Result: {result}")
break
finally:
print("--- End of Transaction ---")
advanced_calculator()
Phase 4: Reflection & Debugging Tools (10 Minutes)
To finish, use the Python Debugger (pdb) on your final code.
1. Add import pdb; pdb.set_trace() at the start of your function.
2. Run the code. The program will freeze at that line.
3. Type n (next) to step through line by line, or p x to print the value of variable x.
Summary Table: Tools in Your Toolkit
Tool Purpose
try Defines the block of code to be tested for
errors.
except Defines how to handle specific errors.
else Executes code if no errors were raised.
finally Executes code regardless of the outcome.
raise Forcing an error to occur based on custom
logic.