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.
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.
| Error type | When it is detected | Who or what detects it | Example |
|---|---|---|---|
| Syntax error | Compile time | The compiler | Missing semicolon; misspelled variable name |
| Run-time error | While the program runs | The JVM, which throws an exception | Integer division by zero |
| Logic error | Testing | A person comparing output to the expected result | Using > where >= was needed |
Naming the Type of Error
Classify each problem as a syntax error, a run-time error (exception), or a logic error.
- The compiler reports ';' expected on line 4.
- A program meant to convert minutes to hours divides by 100 instead of 60. It runs and prints numbers.
- A program stops with
ArithmeticExceptionwhen a class has 0 students. - The compiler reports cannot find symbol for
totl. - A program that should print the larger of two numbers always prints the first one.
- 11: Syntax error. A rule of the language is broken; the compiler detects it.
- 22: Logic error. The code is valid and runs, but the algorithm is wrong.
- 33: Run-time error. Integer division by zero throws an exception while the program runs.
- 44: Syntax error in the broad sense of a compile-time error: an undeclared (misspelled) name is caught by the compiler.
- 55: Logic error. No message appears; the wrong result is the only clue.
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 (
systeminstead ofSystem). - Using a variable that was never declared.
- Storing a value of an incompatible type, such as text in an
intvariable.
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.
Finding Several Syntax Errors
This segment has two syntax errors. Find both.
int laps = 12
System.out.println("Laps run: " + laps;
- 1Error 1. The first statement is missing its semicolon.
- 2Error 2. The
printlncall opens a parenthesis but never closes it before the semicolon. - 3Fix both, then recompile.
Fixed
int laps = 12; System.out.println("Laps run: " + laps);OutputLaps run: 12
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.
| Exception | Typical cause | Example |
|---|---|---|
ArithmeticException | Dividing an integer by zero | total / count when count is 0 |
StringIndexOutOfBoundsException | A string position outside 0 to length − 1 | "cat".substring(2, 5) |
ArrayIndexOutOfBoundsException | An array index outside 0 to length − 1 | Accessing index 5 of a 5-element array |
NullPointerException | Calling a method on a reference that is null | name.length() when name is null |
IndexOutOfBoundsException | A list position outside the valid range | Getting index 3 from a list of size 3 |
An Index That Goes Too Far
The string "chess" has 5 characters at positions 0 through 4. Predict what happens.
String word = "chess";
System.out.println(word.substring(0, 3));
System.out.println(word.substring(3, 6));
- 1First call.
substring(0, 3)returns the characters at positions 0, 1, and 2: "che." It prints normally. - 2Second call.
substring(3, 6)asks for characters up to position 5, but the last position is 4. The program throws aStringIndexOutOfBoundsExceptionand stops. - 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.
StringIndexOutOfBoundsException. Out-of-range positions are classic run-time errors.Calling a Method on null
A variable that refers to no object holds the value null. Predict what happens.
String nickname = null;
System.out.println("Checking nickname...");
System.out.println(nickname.length());
- 1Compile time. The code compiles, because
nicknameis aStringvariable andStringhas alengthmethod. - 2Run time. The first line prints. Then
nickname.length()tries to call a method on no object, throwing aNullPointerException. - 3Prevention. Make sure a reference variable refers to an object before calling its methods.
NullPointerException.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.
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?
int score = 70;
boolean passed = score > 70;
System.out.println(passed);
false
- 1Score 62.
62 > 70isfalse, which is correct. - 2Score 78.
78 > 70istrue, which is correct. - 3Score 70.
70 > 70isfalse, but a 70 should pass. Only the boundary test exposes the logic error. - 4Fix. Use
>=so that 70 itself passes.Fixedint score = 70; boolean passed = score >= 70; System.out.println(passed);Outputtrue
| Test score | Expected passed | Actual with > | Actual with >= | Verdict for > |
|---|---|---|---|---|
| 62 | false | false | false | correct |
| 70 | true | false | true | BUG |
| 78 | true | true | true | correct |
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.
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.
double total = 100.0;
double pay = total;
if (total >= 100)
{
pay = total * 0.9;
}
System.out.println(pay);
90.0
- 1Boundary trio. Test 99.99, 100, and 100.01. Expected results: 99.99 (no discount), 90.0, and about 90.009.
- 2Typical values. Test 40 (pay 40.0) and 250 (pay 225.0).
- 3Check this version. For a total of 100, it prints 90.0, matching the expected result, so the boundary is handled correctly.
- 4Record expected outputs first. Writing down the expected result before running each test prevents accepting whatever the program prints.
6A Debugging Routine
When something goes wrong, a consistent routine saves time:
- Classify the error. Did the code compile? Did it stop with an exception? Or is the output simply wrong? Figure 4 summarizes these questions.
- 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.
- 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.
- 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.
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.
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.