AP® Computer Science Principles · Big Idea 1 · Topic 1.4

Syntax, Logic, and Run-Time Errors

Programs fail in three distinct ways: syntax errors stop a program before it starts, run-time errors crash it mid-execution, and logic errors let it finish while quietly computing the wrong answer.

A program is a set of instructions that takes input and is supposed to produce a correct output. Three kinds of error can break that chain, and they show up at three different moments. A syntax error is a grammar mistake: a missing colon, an unmatched parenthesis, a misspelled keyword. The language's rules are violated, so the translator checks the code before running anything and refuses to start. No statement executes, not even the first one.

A run-time error waits until the program is already running, then hits a step it cannot perform: dividing by zero, asking for the fifth item in a list of three, opening a file that doesn't exist. The program crashes partway through, usually with an error message pointing at the exact line. A logic error is the sneaky one. Nothing is grammatically wrong and nothing crashes, so the program runs start to finish and prints an answer confidently. The answer is just wrong, because the instructions themselves encode the wrong idea. Example: averaging 8 numbers by dividing the sum by 10 instead of 8. It runs fine. It lies fine too.

This is why a clean run with no error messages proves nothing about correctness. Error messages only catch syntax and run-time problems, the ones the language itself can detect. Logic errors are caught only by checking output against known correct answers, which is the whole reason testing with sample data matters once a program runs without crashing.

Key terms

Syntax error
A violation of the language's grammar rules that stops the program from running at all.
Run-time error
An error that occurs while the program is executing, causing it to crash partway through.
Logic error
A flaw in the program's instructions that lets it run to completion but produce an incorrect result.
Translator
The software that checks and converts code into a form the computer can run, catching syntax errors first.

Watch it explained

  1. How it worksHow does a syntax error stop a program before it has run a single statement?
  2. How it worksWalk me through where in the run a syntax error, a logic error, and a run-time error each appear.
  3. Worked exampleFind the logic error in an average routine that divides the total by 10 for a list of 8 numbers.
  4. Common mistakeWhy doesn't the absence of error messages mean a program is correct?

Check yourself

Your turn1 of 2
A list of 7 numbers sums to 202. A logic error makes the averaging routine divide by 15 instead of by the correct count of n. What incorrect value does the routine display?

End of topic.