Topic 08 of 12 | π Lecture 8 β ICT582Topic08.pdf
Testing, Debugging & Exceptions
Catch and raise exceptions, use assertions, and write defensive programs.
π― Learning Objectives
- Explain the three types of errors: syntax, runtime, and logic
- Use
try-exceptto catch and handle exceptions - Use multiple
exceptblocks for different exception types - Raise exceptions using
raise - Use
assertfor testing assumptions in code - Apply defensive programming techniques to validate input
- Use basic debugging strategies (print statements, tracing)
π Key Concepts
Three Types of Errors
| Type | Description | Example |
|---|---|---|
| Syntax Error | Code is grammatically wrong β Python can't even run it | if x == 5 (missing :) |
| Runtime Error | Code runs but crashes during execution | 10 / 0 (ZeroDivisionError) |
| Logic Error | Code runs and gives wrong answer β hardest to find | Using + instead of * |
try-except β Catching Exceptions
Wrap risky code in a try block. If an exception occurs, execution jumps to the matching except block β the program doesn't crash.
try:
x = int(input("Enter a number: "))
result = 100 / x
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("That is not a valid number!")
Common Exception Types
| Exception | When it occurs |
|---|---|
ValueError | Wrong type of value: int("abc") |
TypeError | Wrong type operation: "5" + 5 |
ZeroDivisionError | Division by zero: 10 / 0 |
IndexError | Index out of range: L[10] when L has 3 items |
KeyError | Missing dict key: d["missing"] |
FileNotFoundError | File doesn't exist: open("x.txt") |
NameError | Variable not defined: using x before assigning |
except with else and finally
try:
f = open("data.txt")
data = f.read()
except FileNotFoundError:
print("File not found.")
else:
print("File read successfully!") # runs if NO exception
finally:
print("This always runs.") # runs always (cleanup)
else: runs only if thetryblock succeeded without exceptionfinally: always runs β good for cleanup (closing files)
Catching Any Exception + Getting the Message
try:
risky_operation()
except Exception as e:
print("Error:", e) # prints the error message
raise β Throwing an Exception
You can deliberately trigger an exception to signal an error condition.
def set_age(age):
if age < 0 or age > 150:
raise ValueError(f"Invalid age: {age}")
return age
try:
set_age(-5)
except ValueError as e:
print(e) # Invalid age: -5
assert β Testing Assumptions
assert condition, message β raises AssertionError if condition is False. Used for testing.
def square(n):
return n * n
# Test the function
assert square(4) == 16, "square(4) should be 16"
assert square(0) == 0, "square(0) should be 0"
assert square(-3) == 9, "square(-3) should be 9"
print("All tests passed!") # runs if all asserts pass
Defensive Programming
Anticipate errors before they happen. Validate user input and check preconditions.
def divide(a, b):
if b == 0:
print("Error: cannot divide by zero")
return None
return a / b
# Or use raise:
def divide(a, b):
if b == 0:
raise ValueError("Divisor cannot be zero")
return a / b
Debugging Strategies
- Print statements: add
print()to trace variable values. - Trace by hand: simulate the code step by step on paper.
- Rubber duck debugging: explain your code out loud β you'll spot the bug.
- Simplify: isolate the failing part with a minimal test case.
- Read the error message: Python tells you the type and line number.
π» Code Examples
Example 1 β Robust number input
def get_positive_number():
while True:
try:
n = float(input("Enter a positive number: "))
if n <= 0:
raise ValueError("Must be positive")
return n
except ValueError as e:
print(f"Invalid: {e}. Try again.")
Example 2 β File reading with error handling
try:
with open("config.txt") as f:
data = f.read()
except FileNotFoundError:
print("Config file not found, using defaults.")
data = ""
β οΈ Exam Focus
- Know the 3 error types: syntax (can't run), runtime (crashes), logic (wrong result).
- Trace
try-except: what runs when an exception occurs? What gets skipped? - Know common exceptions:
ValueError,TypeError,ZeroDivisionError,IndexError,KeyError. - Know how to
raisean exception with a message in a function. - Know what
assertdoes β it raisesAssertionErrorif condition is False.
β Common Mistakes
- Catching too broadly with bare
except:β always specify the exception type. - Confusing
elseandfinally:elseruns only on success;finallyalways runs. - Thinking
assertis for runtime validation β asserts can be disabled; useraisefor real validation. - Forgetting that code after the exception line in
tryis skipped when an exception occurs.
β‘ Quick Recap
- 3 error types: Syntax (can't run), Runtime (crashes), Logic (wrong answer).
try: ... except ErrorType: ...β catch and handle runtime errors.elseruns if no exception;finallyalways runs (cleanup).raise ValueError("msg")β signal an error condition manually.assert cond, "msg"β test assumptions; fails with AssertionError.- Defensive programming: validate input before processing it.