ICT582 Python Revision
🎯 Learning Objectives
πŸ“š Key Concepts

Three Types of Errors

TypeDescriptionExample
Syntax ErrorCode is grammatically wrong β€” Python can't even run itif x == 5 (missing :)
Runtime ErrorCode runs but crashes during execution10 / 0 (ZeroDivisionError)
Logic ErrorCode runs and gives wrong answer β€” hardest to findUsing + 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

ExceptionWhen it occurs
ValueErrorWrong type of value: int("abc")
TypeErrorWrong type operation: "5" + 5
ZeroDivisionErrorDivision by zero: 10 / 0
IndexErrorIndex out of range: L[10] when L has 3 items
KeyErrorMissing dict key: d["missing"]
FileNotFoundErrorFile doesn't exist: open("x.txt")
NameErrorVariable 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 the try block succeeded without exception
  • finally: 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
  1. Know the 3 error types: syntax (can't run), runtime (crashes), logic (wrong result).
  2. Trace try-except: what runs when an exception occurs? What gets skipped?
  3. Know common exceptions: ValueError, TypeError, ZeroDivisionError, IndexError, KeyError.
  4. Know how to raise an exception with a message in a function.
  5. Know what assert does β€” it raises AssertionError if condition is False.
❌ Common Mistakes
⚑ Quick Recap
← Topic 07: Files & Strings Topic 09: OOP β†’