Programming Concept

Error Handling

Defensive programming versus exception-based error handling strategies.

Chapter 6 (pp. 151–158) of Computer Science I.

Topics

SectionPageContent
Error Handling153The problem of runtime failure.
Error Handling Strategies153Defensive programming; exceptions.

Key Ideas

Two strategies presented:

  • Defensive programming — validate inputs / check return codes before acting. Realized as POSIX/error codes and enums in C.
  • Exceptions — throw/catch control flow. Realized fully in Java (checked vs unchecked) and PHP.

C lacks native exceptions, so it leans on error codes; this contrast is a deliberate teaching moment across the language parts.

Examples

Defensive programming

function safeDivide(a, b):
  if b = 0:
    return error "division by zero"
  return a / b

Validate before acting — the C-style approach.

Exceptions

try:
  data ← readFile("in.txt")
catch FileNotFound:
  print "missing file"

Separate the happy path from the failure path.

In Java

try {
    String data = readFile("in.txt");
} catch (FileNotFoundException e) {
    System.out.println("missing file");
}

FileNotFoundException is a checked exception — the compiler forces you to catch it or declare throws.

Citations

[1] Computer Science I, Ch. 6, pp. 151–158.