Programming errors are unavoidable, even for experienced programmers. Errors can be categorized into three types: syntax errors, runtime errors, and logic errors.
Errors that occur during compilation are called syntax errors or compilation errors . Syntax errors result from errors in code construction, such as mistyping a keyword, omitting some necessary punctuation, or using an opening brace without a corresponding closing brace . These errors are usually easy to detect, because the compiler tells you where they are and what caused them. For example, compiling the following program results in a syntax error, as shown in Figure 2.11.
// ShowSyntaxErrors.java: The program contains syntax errors public class ShowSyntaxErrors { public static void main(String[] args) { i = 30 ; System.out.println(i + 4 ); } }
Two errors are detected . Both are the result of not declaring variable i . Since a single error will often display many lines of compilation errors, it is a good practice to start debugging from the top line and work downward. Fixing errors that occur earlier in the program may also fix additional errors that occur later.
Runtime errors are errors that cause a program to terminate abnormally. Runtime errors occur while an application is running if the environment detects an operation that is impossible to carry out. Input errors are typical runtime errors.
An input error occurs when the user enters an unexpected input value that the program cannot handle. For instance, if the program expects to read in a number, but instead the user enters a string, this causes data-type errors to occur in the program. To prevent input errors, the program should prompt the user to enter the correct type of values. It may display a message like "Please enter an integer" before reading an integer from the keyboard.
Another common source of runtime errors is division by zero. This happens when the divisor is zero for integer divisions. For instance, the following program would cause a runtime error, as shown in Figure 2.12.
// ShowRuntimeErrors.java: Program contains runtime errors public class ShowRuntimeErrors { public static void main(String[] args) { int i = 1 / ; } }
Logic errors occur when a program does not perform the way it was intended to. Errors of this kind occur for many different reasons. For example, suppose you wrote the following program to add number1 to number2 .
// ShowLogicErrors.java: The program contains a logic error public class ShowLogicErrors { public static void main(String[] args) { // Add number1 to number2 int number1 = 3 ; int number2 = 3 ; number2 += number1 + number2; System.out.println( "number2 is " + number2); } }
The program does not have syntax errors or runtime errors, but it does not print the correct result for number2 . See if you can find the error.