Computer Applications
Explain the following terms, giving an example of each.
i. Syntax error
ii. Runtime error
iii. Logical error
Answer
i. Syntax error
Syntax Errors are the errors that occur when we violate the rules of writing the statements of the programming language. These errors are reported by the compiler and they prevent the program from executing. For example, the following statement will give an error as we missed terminating it with a semicolon:
int sum
ii. Runtime error
Errors that occur during the execution of the program primarily due to the state of the program which can only be resolved at runtime are called Run Time errors.
Consider the below example:
import java.util.Scanner;
class RunTimeError
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = in.nextInt();
int result = 100 / n;
System.out.println("Result = " + result);
}
}
This program will work fine for all non-zero values of n entered by the user. When the user enters zero, a run-time error will occur as the program is trying to perform an illegal mathematical operation of division by 0. When we are compiling the program, we cannot say if division by 0 error will occur or not. It entirely depends on the state of the program at run-time.
iii. Logical error
When a program compiles and runs without errors but produces an incorrect result, this type of error is known as logical error. It is caused by a mistake in the program logic which is often due to human error. Logical errors are not caught by the compiler. Consider the below example for finding the perimeter of a rectangle with length 2 and breadth 4:
class RectanglePerimeter
{
public static void main(String args[]) {
int l = 2, b = 4;
double perimeter = 2 * (l * b); //This line has a logical error
System.out.println("Perimeter = " + perimeter);
}
}
Output
Perimeter = 16
The program gives an incorrect perimeter value of 16 as the output due to a logical error. The correct perimeter is 12. We have written the formula of calculating perimeter incorrectly in the line double perimeter = 2 * (l * b);
. The correct line should be double perimeter = 2 * (l + b);
.
Related Questions
What are errors in a program?
A program has compiled successfully without any errors. Does this mean the program is error free? Explain.
What are delimiters? Which is the default delimiter used in the Scanner class?
If a student forgot to put a closing quotation mark on a string, what kind error would occur?