Error Handling and Testing Your Code
Overview
Before final submission, your project must run without crashing. You'll use exception handling, debugging techniques, and testing strategies to make sure your program behaves as expected, ensuring reliability and professionalism.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- Error handling: Using try-except to handle errors gracefully.
- Testing: Verifying your code works correctly.
- Debugging: Finding and fixing bugs.
- Edge cases: Testing unusual inputs and situations.
- Reliability: Making your project robust and professional.
Why Error Handling Matters
Programs that handle errors gracefully:
Don't Crash
Handle errors instead of stopping unexpectedly
Provide Feedback
Tell users what went wrong and how to fix it
Are More Reliable
Work correctly even with unexpected input
Are Professional
Show attention to detail and user experience
Using Try-Except
Use try-except blocks to handle errors:
# Basic error handling
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ValueError:
print("Error: Please enter a valid number.")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
# File handling with errors
try:
with open("data.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("Error: File not found.")
except PermissionError:
print("Error: Permission denied.")
# General error handling
try:
# Your code here
pass
except Exception as e:
print(f"An error occurred: {e}")
Best Practice
Be specific with exception types. Catch ValueError or FileNotFoundError rather than generic Exception when possible.
Testing Your Code
Test your project thoroughly:
Test Normal Cases
Verify features work with expected input
Test Edge Cases
Try empty input, very long input, boundary values
Test Error Cases
Verify error handling works correctly
Fix Issues
Address any problems you find
def test_add_task():
"""Test adding a task."""
tasks = []
tasks = add_task(tasks, "Buy groceries")
assert len(tasks) == 1
assert tasks[0]["name"] == "Buy groceries"
print("✓ Test passed!")
# Test edge cases
def test_empty_input():
"""Test handling empty input."""
try:
result = process_input("")
assert False, "Should have raised an error"
except ValueError:
print("✓ Empty input handled correctly!")
Summary
In this lesson, you learned:
- Error handling: Use try-except to handle errors gracefully
- Testing: Test normal cases, edge cases, and error cases
- Reliability: Make your project robust and professional
- Best practices: Be specific with exceptions, test thoroughly
Remember
Error handling and testing are essential for professional projects. Take time to test thoroughly and handle errors gracefully. Your users will appreciate it!
End-of-Lesson Exercises
Think about these questions to reinforce what you've learned:
Exercise 1: Error Handling
Why is error handling important? How do you use try-except blocks?
Exercise 2: Testing
What should you test in your project? What are edge cases?