Errors in Java | Runtime & Compile Time Errors

Errors in Java occur when a programmer violates the rules of Java programming language. It might be due to programmer’s typing mistakes while developing a program. It may produce incorrect output or may terminate the execution of the program abnormally.

For example, if you use a right parenthesis in a Java program where a right brace is needed, you have made a syntax error. You have violated the rules of Java language.

Therefore, it is important to detect and fix properly all errors occurring in a program so that the program will not terminate during execution.

Types of Errors in Java Programming


When we write a program for the first time, it usually contains errors. These errors are mainly divided into three types:
1. Compile-time errors (Syntax errors)
2. Runtime errors

3. Logical errors

Types of errors in Java programming

Java Compile Time Errors


Compile time errors occur when syntactical problems occur in a java program due to incorrect use of Java syntax. These syntactical problems may be missing semicolons, missing brackets, misspelled keywords, use of undeclared variables, class not found, missing double-quote in Strings, and so on. These problems occurring in a program are called syntax errors in Java.


Since all syntax errors are detected by Java compiler, therefore, these errors are also known as compile time errors in Java. When Java compiler finds syntax errors in a program, it prevents the code from compile successfully and will not create a .class file until errors are not corrected. An error message will be displayed on the console screen.

These errors must be removed by debugging before successfully compile and run the program. Let’s take an example program where we will get a syntax error. 

Program source code 1:

public class CompileTimeErrorEx 
{
public static void main(String[] args) 
{
  System.out.println("a") // Syntax error. Semicolon missing.
 }
}
Compile time error in Java code:
      Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Syntax error, insert ";" to complete BlockStatements

When you will try to compile the above program, Java compiler will tell you where errors are in the program. Then you can go to the appropriate line, correct error, and recompile the program. 

Let’s create a program where we will try to call the undeclared variable. In this case, we will get unresolved compilation problem.

Program source code 2:

public class MisspelledVar 
{	
public static void main(String[] args) 
{
int x = 20, y = 30;

// Declare variable sum.
   int sum = x + y; 

// Call variable Sum with Capital S.
   System.out.println("Sum of two numbers: " + Sum); // Calling of undeclared variable.
 }
}
Compile time error in Java code:
       Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Sum cannot be resolved to a variable

Program source code 3: Missing parenthesis in for statement.

public class MissingBracket 
{	
public static void main(String[] args) 
{ 
 int i; 
 int sum = 0;

// Missing bracket in for statement.
 for (i = 1; i <= 5; i++ // insert " ) Statement" to complete For Statement.
 {
   sum = sum + i;	
 }
System.out.println("Sum of 1 to 5 \n");
System.out.println(sum); 
  }
}
Compile time error in Java code:
      Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Syntax error, insert ") Statement" to complete ForStatement

Program source code 4: Missing double quote in String literal.

public class MissingDoubleQuote
{	
public static void main(String[] args) 
{ 
 String str = "Scientech; // Missing double quote in String literal.
 System.out.println(str);
  }
}
Compile time error in Java code:
       Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	String literal is not properly closed by a double-quote

We may also face another error related to the directory path. An error such as

javac : command not found

means that you have not set the path correctly. 

Runtime Errors in Java


Runtime errors occur when a program is successfully compiled creating the .class file but do not run properly. It is detected at run time (i.e. during the execution of the program).


Java compiler has no technique to detect runtime errors during compilation because a compiler does not have all of the runtime information available to it. JVM is responsible to detect runtime errors while the program is running.

Such program that contains runtime errors, may produce wrong results due to wrong logic or terminate the program. These runtime errors are usually known as exceptions.

For example, if a user inputs a value of string type in a program but the computer is expecting an integer value, a runtime error will be generated.

Most common runtime errors are as follows:
1. Dividing an integer by zero.
2. Accessing an element that is out of range of the array.
3. Trying to store a value into an array that is not compatible type.
4. Passing an argument that is not in a valid range or valid value for a method.
5. Striving to use a negative size for an array.
6. Attempting to convert an invalid string into a number.
7. and many more.

When such errors are encountered in a program, Java generates an error message and terminate the program abnormally. To handle these kinds of errors during the runtime, we use exception handling technique in java program.

Let’s take different kinds of example programs to understand better.

Program source code 5: In this program, we will divide an integer number by zero. Java compiler cannot detect it.

public class DivisionByZeroError
{	
public static void main(String[] args) 
{ 
 int a = 20, b = 5, c = 5;
 int z = a/(b-c); // Division by zero.
 
 System.out.println("Result: " +z);
  }
}
Output:
       Exception in thread "main" java.lang.ArithmeticException: / by zero
	at errorsProgram.DivisionByZeroError.main(DivisionByZeroError.java:8)

The above program is syntactically correct. There is no syntax error and therefore, does not cause any problem during compilation. While executing, runtime error occurred that is not detected by compiler.

The error is detected by JVM only in runtime. Default exception handler displays an error message and terminates the program abnormally without executing further statements in the program.

Program source code 6: In this program, we will try to retrieve a value from an array using an index that is out of range of the array.

public class AccessingValueOutOfRangeError
{	
public static void main(String[] args) 
{ 
 int arr[] = {1, 2, 3, 4, 5}; // Here, array size is 5.

 System.out.println("Value at 5th position: "+arr[5]);
  }
}
Output:
       Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
	at errorsProgram.AccessingValueOutOfRangeError.main(AccessingValueOutOfRangeError.java:9)

Logical Errors in Java Program


Logical errors in Java are the most critical errors in a program and they are difficult to detect. These errors occur when the programmer uses incorrect logic or wrong formula in the coding. The program will be compiled and executed successfully but does not return the expected output.

Logical errors are not detected either by Java compiler or JVM (Java runtime system). The programmer is entirely responsible for them. They can be detected by application testers when they compare the actual result with its expected result.

For example, a programmer wants to print even numbers from an array but he uses division (/) operator instead of modulus (%) operator to get the remainder of each number. Due to which he got wrong results.

Let’s see the following source code related to this problem.

Program source code 7:

public class LogicalErrorEx
{	
public static void main(String[] args) 
{ 
 int a[]={1, 2 , 5, 6, 3, 10, 12, 13, 14};  
 
System.out.println("Even Numbers:");  
for(int i = 0; i <a.length; i++)
{  
if(a[i] / 2 == 0) // Using wrong operator.
{  
  System.out.println(a[i]);  
 }  
}  
 }
}
Output:
       Even Numbers:
       1

As you can see that program is successfully compiled and executed but the programmer got the wrong output due to logical errors in the program.

Final words
Seldom does a program run successfully at its first attempt. A software engineer in a company also commits several errors while designing the project or developing code. These errors in a program are also called bugs and the process of fixing these bugs is called debugging.

All modern integrated development environments (IDEs) such as Eclipse, NetBeans, JBuilder, etc provide a tool known as debugger that helps to run the program step by step to detect bugs. In this tutorial, we have familiarized different types of errors in java that may possibly occur in a program.

Thanks for reading!!!