AP Computer Science Principles

1.4 — Identifying and Correcting Errors

Debugging: finding, understanding, and fixing mistakes so programs behave as intended.

Overview

All programmers make mistakes. The key skill is learning how to find, understand, and fix those mistakes. In AP CSP, you practice debugging — a systematic process of identifying and correcting errors so a program behaves as intended.

1) Types of Errors

Type When it Happens Example How to Fix It
Syntax Error When the code violates language rules. Missing parenthesis or misspelled keyword. Read error messages; fix punctuation or spelling.
Logic Error The program runs but gives wrong results. Using + instead of - in a formula. Trace with prints; compare expected vs. actual behavior.
Runtime Error The program crashes while running. Divide by zero; index out of range; null reference. Add checks/guards; handle exceptional conditions.

Tip: Syntax errors usually stop code from running. Logic and runtime errors often allow it to run incorrectly.

2) The Debugging Process

  1. Reproduce the Error — Run the program to see exactly when and where it fails.
  2. Read the Error Message — Note the line and description the system provides.
  3. Isolate the Problem — Test small parts or comment out sections to narrow it down.
  4. Predict the Cause — Compare intended behavior with actual behavior.
  5. Repair the Code — Adjust statements, variables, or control flow.
  6. Retest & Verify — Rerun with multiple cases (including edge inputs).

3) Common Debugging Techniques

  • Print Debugging — Show variable values at key points.
  • Walkthrough — Manually trace code step-by-step.
  • Rubber Duck Debugging — Explain your code out loud.
  • Peer Review — Get a second set of eyes.
  • Debugger Tools — Use breakpoints and step execution in an IDE.

4) Importance of Testing

  • Try both expected and unexpected inputs.
  • Create edge cases (very large/small numbers, empty strings, etc.).
  • Automate tests when possible to catch regressions.

A good program doesn’t just work — it fails safely with helpful messages.

5) Example — Safe Division

Goal: Divide two numbers without crashing.

Original Pseudocode (with error):

num1 ← INPUT
num2 ← INPUT
result ← num1 / num2
DISPLAY result

Problem: When num2 = 0, program crashes (runtime error).

Fixed Version:

num1 ← INPUT
num2 ← INPUT
IF num2 ≠ 0 THEN
    result ← num1 / num2
    DISPLAY result
ELSE
    DISPLAY "Error: Cannot divide by zero."
END IF

Summary — Skills at a Glance

Skill Purpose
Identify errors Recognize syntax, logic, and runtime problems.
Debug systematically Follow a repeatable process to locate issues.
Test programs Use varied inputs and edge cases to validate correctness.
Correct & refine Modify and verify code until results match expectations.