AP Computer Science A · Study guide

Programming Error Types

AP® Computer Science A · Using Objects and Methods

Programming Error Types

The three kinds of programming errors, when each one appears, how to read the messages Java gives, and how to design tests that expose the errors no message will ever report.

Big Picture

Every programmer makes mistakes; what matters is finding them quickly. Errors fall into three types. Syntax errors break the rules of the language and are caught by the compiler. Run-time errors happen while the program is running and usually stop it; an exception is a run-time error that interrupts the normal flow of the program. Logic errors make a program behave incorrectly without any message at all, and are found only by testing with specific data. Knowing which type you are facing tells you where to look and how to fix it.

1Three Kinds of Errors

The three error types differ in when they appear and who notices them. A syntax error is noticed by the compiler before the program runs. A run-time error is noticed by the Java Virtual Machine while the program runs, usually as an exception that ends the program. A logic error is noticed only by a person, or an automated test, comparing what the program does with what it should do.

This order matters for debugging. Syntax errors come with a line number and a description, so they are usually the easiest to fix. Run-time errors also come with a message and a line number, but you must work out which value caused the problem. Logic errors give no clues except wrong behavior, so they demand careful testing and tracing.

Figure 1. Syntax errors are caught by the compiler before the program runs. Run-time errors stop a running program. Logic errors produce no message at all; only testing reveals them.
Error typeWhen it is detectedWho or what detects itExample
Syntax errorCompile timeThe compilerMissing semicolon; misspelled variable name
Run-time errorWhile the program runsThe JVM, which throws an exceptionInteger division by zero
Logic errorTestingA person comparing output to the expected resultUsing > where >= was needed
Worked Example 1 Classification

Naming the Type of Error

Classify each problem as a syntax error, a run-time error (exception), or a logic error.

  1. The compiler reports ';' expected on line 4.
  2. A program meant to convert minutes to hours divides by 100 instead of 60. It runs and prints numbers.
  3. A program stops with ArithmeticException when a class has 0 students.
  4. The compiler reports cannot find symbol for totl.
  5. A program that should print the larger of two numbers always prints the first one.
  1. 11: Syntax error. A rule of the language is broken; the compiler detects it.
  2. 22: Logic error. The code is valid and runs, but the algorithm is wrong.
  3. 33: Run-time error. Integer division by zero throws an exception while the program runs.
  4. 44: Syntax error in the broad sense of a compile-time error: an undeclared (misspelled) name is caught by the compiler.
  5. 55: Logic error. No message appears; the wrong result is the only clue.
Result: Problems 1 and 4 are caught by the compiler, problem 3 stops the running program, and problems 2 and 5 are logic errors found only by testing.

2Syntax Errors

A syntax error is a mistake in which the rules of the programming language are not followed. Like grammar rules in English, Java's syntax rules govern how statements are formed: statements end with semicolons, parentheses and braces come in matching pairs, keywords are spelled exactly, and names are used consistently. Syntax errors are detected by the compiler, and the program cannot run until they are fixed.

Common syntax errors include:

  • A missing semicolon at the end of a statement.
  • Unmatched parentheses, brackets, or braces.
  • Misspelled keywords or names, including wrong capitalization (system instead of System).
  • Using a variable that was never declared.
  • Storing a value of an incompatible type, such as text in an int variable.

Strictly, the last two are type and name errors rather than grammar errors, but they are found the same way: by the compiler, before the program runs.

Worked Example 2 Syntax errors

Finding Several Syntax Errors

This segment has two syntax errors. Find both.

Code that does not compile
int laps = 12
System.out.println("Laps run: " + laps;
  1. 1Error 1. The first statement is missing its semicolon.
  2. 2Error 2. The println call opens a parenthesis but never closes it before the semicolon.
  3. 3Fix both, then recompile.
    Fixed
    int laps = 12;
    System.out.println("Laps run: " + laps);
    Output
    Laps run: 12
Result: A missing semicolon and a missing closing parenthesis are both syntax errors. After fixing them, the segment prints "Laps run: 12."
Common Mistake 1 · Fixing the Wrong Line

The compiler reports where it noticed the problem, which is often the line after the real mistake. If a missing semicolon on line 3 is reported on line 4, editing line 4 will not help. When the reported line looks correct, check the end of the previous line, and fix the first reported error before reading the rest.

3Run-Time Errors and Exceptions

A run-time error is a mistake that occurs during the execution of a program. Run-time errors typically cause the program to terminate abnormally. An exception is a type of run-time error that occurs because of an unexpected situation the compiler could not detect, such as dividing an integer by zero or asking for a position past the end of a string. When an exception occurs, it interrupts the normal flow of execution: the statements that already ran have produced their output, and the statements after the failing one never run.

The compiler cannot catch these errors because they depend on values that exist only while the program runs. The expression total / count is fine when count is 4 and fails when count is 0, and the compiler cannot know which will happen.

Figure 2. When an exception stops a program, the message names the exception, gives a short description, and reports the line that was running. That line is the starting point for finding the cause.
ExceptionTypical causeExample
ArithmeticExceptionDividing an integer by zerototal / count when count is 0
StringIndexOutOfBoundsExceptionA string position outside 0 to length − 1"cat".substring(2, 5)
ArrayIndexOutOfBoundsExceptionAn array index outside 0 to length − 1Accessing index 5 of a 5-element array
NullPointerExceptionCalling a method on a reference that is nullname.length() when name is null
IndexOutOfBoundsExceptionA list position outside the valid rangeGetting index 3 from a list of size 3
Worked Example 3 Run-time errors

An Index That Goes Too Far

The string "chess" has 5 characters at positions 0 through 4. Predict what happens.

Code
String word = "chess";
System.out.println(word.substring(0, 3));
System.out.println(word.substring(3, 6));
  1. 1First call. substring(0, 3) returns the characters at positions 0, 1, and 2: "che." It prints normally.
  2. 2Second call. substring(3, 6) asks for characters up to position 5, but the last position is 4. The program throws a StringIndexOutOfBoundsException and stops.
  3. 3Why the compiler did not complain. Whether 6 is too large depends on the length of the string, which is a value examined while the program runs.
Result: The program prints "che" and then stops with a StringIndexOutOfBoundsException. Out-of-range positions are classic run-time errors.
Worked Example 4 Run-time errors

Calling a Method on null

A variable that refers to no object holds the value null. Predict what happens.

Code
String nickname = null;
System.out.println("Checking nickname...");
System.out.println(nickname.length());
  1. 1Compile time. The code compiles, because nickname is a String variable and String has a length method.
  2. 2Run time. The first line prints. Then nickname.length() tries to call a method on no object, throwing a NullPointerException.
  3. 3Prevention. Make sure a reference variable refers to an object before calling its methods.
Result: The program prints "Checking nickname..." and then stops with a NullPointerException.
Common Mistake 2 · Thinking an Exception Is a Syntax Error

An exception means the code compiled successfully and started running. Reorganizing semicolons and braces will not fix it. Instead, find the line named in the message and ask which value at that moment made the operation impossible: a zero divisor, a position that is too large, or a reference that is null.

4Logic Errors

A logic error is a mistake in the algorithm or program that causes it to behave incorrectly or unexpectedly. The code follows every rule, compiles, and runs to completion, but the result is wrong: an average that ignores one score, a loop that stops one step early, a comparison that uses > where >= was needed.

Because there is no error message, logic errors are detected by testing the program with specific data and checking whether it produces the expected outcome. They are often the hardest errors to find, and they can hide for a long time if the program is only tested on typical values that happen to give correct answers.

Worked Example 5 Logic errors

A Boundary Bug Found by Testing

A quiz is passed with a score of 70 or higher. Test this code with the scores 62, 70, and 78. Which test reveals the bug?

Code
int score = 70;
boolean passed = score > 70;
System.out.println(passed);
Output
false
  1. 1Score 62. 62 > 70 is false, which is correct.
  2. 2Score 78. 78 > 70 is true, which is correct.
  3. 3Score 70. 70 > 70 is false, but a 70 should pass. Only the boundary test exposes the logic error.
  4. 4Fix. Use >= so that 70 itself passes.
    Fixed
    int score = 70;
    boolean passed = score >= 70;
    System.out.println(passed);
    Output
    true
Result: Typical values hid the bug; the boundary value 70 revealed it. Testing on and around every cutoff, as in Figure 3, is the most effective way to catch comparison mistakes.
Test scoreExpected passedActual with >Actual with >=Verdict for >
62falsefalsefalsecorrect
70truefalsetrueBUG
78truetruetruecorrect
Common Mistake 3 · Testing Only Easy Cases

If every test uses comfortable, typical values, boundary mistakes slip through. In the passing-score example, scores of 62 and 78 both gave correct answers with the buggy code. Only 70, the cutoff itself, revealed the error. Always include values on and next to every boundary in a condition.

5Testing to Find Errors

Testing means running a program with chosen inputs and comparing its actual output with the expected output. Useful tests are planned, not random:

  • Typical cases check that the program works for ordinary inputs.
  • Boundary cases sit exactly on and just beside every cutoff in a condition, such as 69, 70, and 71 for a passing score of 70.
  • Special cases include zero, empty strings, and the smallest and largest expected values, which often trigger run-time errors.

For every test, write the expected result before running the program. Otherwise it is too easy to look at whatever the program prints and decide it seems reasonable.

Figure 3. Good tests include typical values and values on and next to every boundary. Logic errors in comparisons hide at the boundary, where most other test values cannot see them.
Worked Example 6 Testing

Designing Tests for a Discount Rule

A store gives 10% off orders of at least 100 dollars. A programmer writes the code below. Design a set of tests that would expose any mistake in the comparison or the arithmetic, and use them to check this version.

Code
double total = 100.0;
double pay = total;
if (total >= 100)
{
    pay = total * 0.9;
}
System.out.println(pay);
Output
90.0
  1. 1Boundary trio. Test 99.99, 100, and 100.01. Expected results: 99.99 (no discount), 90.0, and about 90.009.
  2. 2Typical values. Test 40 (pay 40.0) and 250 (pay 225.0).
  3. 3Check this version. For a total of 100, it prints 90.0, matching the expected result, so the boundary is handled correctly.
  4. 4Record expected outputs first. Writing down the expected result before running each test prevents accepting whatever the program prints.
Result: A strong test set mixes typical values with values on and beside the 100-dollar boundary, each with its expected result written in advance. This version passes the boundary test.

6A Debugging Routine

When something goes wrong, a consistent routine saves time:

  1. Classify the error. Did the code compile? Did it stop with an exception? Or is the output simply wrong? Figure 4 summarizes these questions.
  2. Find where it starts. For syntax and run-time errors, start at the reported line and the line just before it. For logic errors, find the first point where a value differs from what you expect.
  3. Trace by hand. Track the value of each variable statement by statement, as in a trace table. Adding temporary print statements that show intermediate values is a quick way to see what the program is actually doing.
  4. Make one change, then retest. Changing several things at once makes it hard to know which change fixed the problem, or which one created a new one.
Figure 4. Three questions classify almost any error. A passing test does not prove the program is correct; it shows only that no error appeared for that input.
Common Mistake 4 · Changing Code at Random Until It Works

Making guesses without understanding the error can accidentally hide a bug for one test while breaking another. Before changing anything, be able to explain why the current code produces the output it does. A fix you can explain is a fix you can trust.

Four Habits for Handling Errors

1. Classify First

Compile error, run-time exception, or wrong output: each needs a different search.

2. Read the Message Fully

Exception names and line numbers point to the failing operation.

3. Test the Boundaries

Check values on and next to every cutoff, plus zero and empty cases.

4. Expected Before Actual

Write the correct answer down before you run each test.

Core Synthesis

A syntax error is a mistake in which the rules of the programming language are not followed; it is detected by the compiler. A logic error is a mistake in the algorithm or program that causes it to behave incorrectly or unexpectedly; it is detected by testing the program with specific data to see whether it produces the expected outcome. A run-time error occurs during execution and typically causes the program to terminate abnormally. An exception is a type of run-time error that occurs because of an unexpected situation not detected by the compiler, and it interrupts the normal flow of the program.