AP COMPUTER SCIENCE PRINCIPLES • CREATIVE DEVELOPMENT

Identifying and Correcting Errors

Master the systematic process of finding, classifying, and fixing bugs to build reliable programs.

Historical Context & Motivation

Software errors—commonly called bugs—have shaped computing history since the field's earliest days. The term itself traces back to the 1940s, when engineers working on the Harvard Mark II found a moth lodged in a relay, causing the machine to malfunction. Although the word 'bug' had been used informally in engineering circles before that incident, Grace Hopper's famous log entry cemented it in the computing lexicon. Since then, identifying and correcting errors has grown from an ad-hoc troubleshooting activity into a rigorous discipline with formal methods, automated tools, and structured workflows that every programmer must master.

1947
The First Literal 'Bug'
Engineers log a moth found in the Harvard Mark II relay, popularizing the term 'debugging' in computer science.
1962
Mariner 1 Failure
A missing hyphen in a guidance program causes the Mariner 1 rocket to veer off course, demonstrating that a single syntax error can have catastrophic consequences.
1996
Ariane 5 Overflow
A 64-bit to 16-bit integer conversion overflow destroys the ESA's Ariane 5 rocket seconds after launch—a runtime error worth $370 million.
2000s
Rise of Automated Testing
Unit testing frameworks, continuous integration, and static analysis tools become standard practice, shifting debugging from reactive to preventive.

These milestones illustrate a central truth: errors are inevitable in software development, and the ability to find and fix them systematically separates competent programmers from novices. The AP Computer Science Principles exam expects you to classify errors by type, trace through code to locate faults, and describe strategies for correction. This lesson equips you with the conceptual framework and hands-on techniques to do exactly that.

Core Principles & Definitions

Before diving into debugging strategies, it is essential to understand the four primary categories of errors you will encounter. The College Board's framework distinguishes among syntax errors, logic errors, runtime errors, and overflow errors. Each manifests differently, requires different detection techniques, and demands different correction strategies.

1

Syntax Errors

Violations of the programming language's grammatical rules—missing parentheses, misspelled keywords, or incorrect punctuation. Caught before execution by the compiler or interpreter.
2

Logic Errors

The program runs without crashing but produces incorrect results. Caused by flawed algorithms, wrong operators, or off-by-one mistakes. Hardest to detect because no error message appears.
3

Runtime Errors

Errors that occur during execution, causing the program to crash or halt unexpectedly—dividing by zero, accessing an out-of-bounds index, or running out of memory.
4

Overflow Errors

Occur when a computed value exceeds the maximum representable value for a given data type. The result wraps around or is truncated, producing incorrect output silently in some languages.
KEY TAKEAWAY
KEY TAKEAWAY

Visual Explanation — Error Taxonomy

This flowchart shows the decision process for classifying an error. Start at the top: if the program fails to compile, it is a syntax error. If it compiles but crashes, it is a runtime error. If it runs to completion but produces wrong output, it is a logic error. Overflow errors are a special subtype that can manifest as either runtime or logic errors depending on the language.

The flowchart above encapsulates the diagnostic reasoning you should apply whenever you encounter unexpected behavior. Notice that syntax errors are the easiest to find because development tools flag them automatically, while logic errors require the programmer to know the expected output and compare it against the actual output. On the AP exam, questions often present a code segment and ask you to determine both the type of error and how to fix it—so internalizing this decision tree is crucial.

How Errors Manifest — Deep Dive

Syntax Errors in Detail

A syntax error occurs when your code violates the grammar rules that the language processor expects. In text-based languages, common culprits include missing semicolons, unmatched brackets, misspelled keywords, and incorrect indentation (in Python, where whitespace is syntactically meaningful). In the AP CSP exam's pseudocode, forgetting the closing brace of an IF block or misplacing the REPEAT keyword would constitute a syntax error. The key distinguishing feature is that the program never begins to execute—the interpreter or compiler halts and typically provides an error message with a line number.

Runtime Errors in Detail

Runtime errors pass the parsing stage but cause the program to terminate abnormally during execution. Division by zero is the canonical example: the expression x / y is syntactically valid, but if y = 0 at execution time, the operation is undefined and the program crashes. Other common runtime errors include attempting to access an element at an index that exceeds the list's length, calling a procedure with the wrong number of arguments in dynamically-typed languages, and infinite recursion that exhausts the call stack. The AP exam frequently tests whether students can identify inputs that would trigger a runtime error in otherwise syntactically correct code.

Logic Errors in Detail

Logic errors are the most insidious category because the program runs to completion without any error message—it simply produces the wrong answer. Classic examples include using < instead of <= in a loop condition (off-by-one error), adding instead of multiplying in a formula, or initializing an accumulator to 1 instead of 0. Detecting logic errors requires you to hand-trace the code with known inputs and compare the expected output to the actual output. If the two differ, there is a logic error lurking in the algorithm.

Overflow Errors in Detail

Every number stored in a computer has a finite number of bits allocated to represent it. When an arithmetic operation produces a result that exceeds the maximum (or minimum) value that can be stored, an overflow error occurs. In some languages, the value wraps around silently—a large positive integer might suddenly become negative—while in others, the program throws an exception. On the AP exam, you should understand that adding two large positive integers can yield a negative result in fixed-width representations, and that this is fundamentally a consequence of the finite nature of digital data storage.

Debugging Strategies & Testing

The debugging cycle consists of six iterative stages: reproduce the bug reliably, isolate the region of code responsible, diagnose the root cause by tracing, fix the code, test the fix against original and edge-case inputs, and reflect on what caused the error. If the test fails, the cycle repeats.

Key Testing Strategies

Common debugging strategies tested on the AP CSP exam
StrategyDescriptionBest For
Hand TracingStep through code line by line on paper, tracking variable values in a table.Logic errors, small code segments, AP exam questions
Print / Display StatementsInsert DISPLAY or print commands to output variable values at key points during execution.Runtime and logic errors during development
Edge-Case TestingTest with boundary inputs: 0, negative numbers, empty lists, very large values.Overflow and runtime errors
Pair DebuggingExplain code logic to a collaborator line by line; fresh eyes often spot mistakes the author overlooks.Logic errors, collaborative development

The AP exam does not require you to use a specific debugging tool, but it does expect you to describe how you would use these strategies to locate and correct an error. For the Create Performance Task, documenting your testing process—what inputs you tried, what output you expected versus what you observed, and how you corrected the discrepancy—is an integral part of demonstrating program development.

Worked Example — Tracing & Fixing a Logic Error

Consider the following pseudocode intended to compute the average of a list of numbers:

ORIGINAL CODE (BUGGY)
1
Step 1 — Reproduce the ErrorRun the code with numList ← [10, 20, 30]. Expected output: 20. Actual result: the program crashes with a division-by-zero error because count is 0.
Runtime error: division by zero
2
Step 2 — Isolate the CauseThe variable count is initialized to 0 but never incremented inside the loop. The loop only accumulates sum. When we reach the division, count is still 0.
3
Step 3 — Diagnose the Root CauseThis is a logic error in the algorithm: the programmer intended to count elements but forgot to include the statement count ← count + 1 inside the FOR EACH loop. The omission causes a secondary runtime error (division by zero).
4
Step 4 — Fix the CodeAdd count ← count + 1 inside the loop body, right after the sum accumulation line.
5
Step 5 — Test the FixHand trace with [10, 20, 30]: After the loop, sum = 60, count = 3. average = 60 / 3 = 20. Also test edge cases: an empty list (count = 0 would still cause division by zero—add a guard condition) and a single-element list.
Output: 20 ✓
CORRECTED CODE

Comparing Error Types — Strengths & Limitations of Detection

Detection difficulty and correction strategies by error type
Error TypeDetection DifficultyTypical Detection MethodCommon Correction
SyntaxEasy — caught automaticallyCompiler / interpreter error messages with line numbersFix the typo, add missing punctuation, correct indentation
RuntimeModerate — requires triggering inputCrash messages, edge-case testing, exception handlingAdd input validation, boundary checks, guard clauses
LogicHard — no automatic detectionHand tracing, print statements, comparing expected vs. actual outputRevise algorithm, fix operators, correct loop bounds
OverflowHard — may be silentTesting with extreme values, understanding data type limitsUse larger data types, check bounds before arithmetic
KEY TAKEAWAY
KEY TAKEAWAY

Connection to Professional Software Development

The error identification skills tested on the AP CSP exam form the foundation of professional software engineering practices. In industry, the concepts scale dramatically: syntax errors are caught by linters and integrated development environments before code is even committed; runtime errors are managed through structured exception handling (try/catch blocks); logic errors are prevented through automated test suites that run thousands of checks continuously; and overflow errors are addressed through careful use of arbitrary-precision libraries and formal verification methods.

How AP CSP debugging concepts scale to professional practice
AP CSP ConceptProfessional Equivalent
Hand tracingInteractive debuggers (breakpoints, stepping, watch variables)
Print / DISPLAY statementsLogging frameworks (structured, leveled logging)
Testing with multiple inputsUnit tests, integration tests, continuous integration pipelines
Pair debugging / collaborationCode reviews, pair programming, pull request workflows
Identifying overflow potentialStatic analysis tools, type systems, fuzzing

Understanding error types at the conceptual level prepares you not only for the AP exam but also for any future coursework in software engineering, data science, or systems design. The systematic thinking—reproduce, isolate, diagnose, fix, test—transfers universally to any programming language or development environment.

Practice Problems

1
A student writes a program that compiles and runs successfully, but the output is always 5 more than the expected result. What type of error does this describe?
2
Consider the following pseudocode: x ← 10 y ← 0 result ← x / y DISPLAY(result) What happens when this code is executed?
3
A programmer writes a procedure to find the maximum value in a list. The procedure initializes max ← 0 then iterates through the list, updating max whenever a larger value is found. Select two inputs that would cause the procedure to return an incorrect result.
PROBLEM 4APPLIED
A student writes the following pseudocode to count how many times a target value appears in a list: PROCEDURE countOccurrences(myList, target) { count ← 1 FOR EACH item IN myList { IF (item = target) { count ← count + 1 } } RETURN count } (a) Identify the error in this code. (b) Classify the error type. (c) Describe how to correct the error. (d) Give a specific test case (input and expected vs. actual output) that reveals the error.
PROBLEM 5CRITICAL THINKING
A team is developing a program that computes shipping costs. The procedure below is intended to apply a 10% discount if the total exceeds $100 and then add a flat $5 shipping fee. PROCEDURE calcShipping(total) { IF (total > 100) { total ← total * 0.10 } shipping ← total + 5 RETURN shipping } (a) Identify and classify all errors in this procedure. (b) For each error, explain why it produces an incorrect result by hand-tracing the code with the input total = 120. (c) Write corrected pseudocode that fixes all errors. (d) Describe two additional test cases (beyond total = 120) you would use to verify the corrected procedure works, including expected outputs. (e) Explain how a developer might have prevented these errors during the initial development process.
Varsity Tutors • AP Computer Science Principles • Identifying and Correcting Errors