While working with the programming languages like executing a software program, there are many instances that we run into issues due to the run time errors or compilation errors. All these errors occur when the application is running. You might come across an instance where the application acts differently in a negative way to the requirements, then it means that a runtime error took place.
As it is one of the most common type of error that occurs during a software executive, let us get a deep idea on how to fix common types of runtime errors in Java and also the steps to be taken to resolve them on a timely basis.
Fix the 5 Most Common Types of Runtime Errors in Java
What is a Runtime Error in Java?
A runtime error in Java is referred to as an application error that comes up during the execution process of the program. This runtime error usually takes place when the syntax is corrected as expected while the issue lies during the program execution. All these errors can be detected by JVM – Java Virtual Machine and cannot be identified during the compilation time. Java is one of the most sought-after programming languages for the hiring managers across the world. So become an expert in Java through our Java Training and grab the best job opportunity.
Now, In this post, Let us discuss the top runtime errors in Java.
- Division by zero errors
- IO errors
- Out of range errors
- Undefined object errors
Differences Between Compile Time Error and Runtime Error in Java
Compile time errors are those errors in which the syntax would be incorrect in the application code. An example would be like missing semicolons, parenthesis, incorrect keywords, usage of undeclared variables, etc.
The Java compiler is capable of detecting the syntax errors during the compile time and the error message will be appearing on the screen. The compiler is also capable of preventing the code from the execution unless and until the error is resolved. Therefore it is important that these errors are addressed by making the necessary changes before the program is successfully executed.
The runtime errors occur during the program execution after the compilation has completed. Any program that is throwing a runtime error means that there are no issues with Syntax in the program.
Why Runtime Error Occurs in Java ?
Below listed are the most common types of runtime errors that occur in Java.
- Accessing an element that is out of range in an array
- Dividing a number with 0
- Less space or insufficient space memory
- Conversion of an invalid string into a number
- Attempting to store an incompatible value to a collection
When you come across such an address, you need to know that the Java compiler will be generating an error message and the program gets terminated abnormally. Runtime errors do not require to be caught explicitly. It is useful if you catch the runtime errors and resolve them to complete the program execution.
Let us review a few of the most common runtime errors in Java programming with examples to gain a deeper understanding.
1. Accessing Out of Range Value in an Array
1 2 3 4 5 6 |
public class ValueOutOfRangeErrorExample { public static void main(String[] args) { int k[] = new int[8]; System.out.println("8th element in array: " + k[8]); } } |
Error :
1 2 3 |
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 8 out of bounds for length 8 at ValueOutOfRangeErrorExample.main(ValueOutOfRangeErrorExample.java:4) |
2. Division by Zero Error
Below is an example of java.lang.ArithmeticException which occurs when the user is trying to code in such a way that they perform the division by zero.
1 2 3 4 5 6 |
public class ArithmeticExceptionExample { public static void main(String[] args) { int num1 = 10, num2 = 0; System.out.println("Result: "+ num1/num2); } } |
In the above code, the integer num1 is getting to be divided by num2 which has a value of zero, which is leading to the exception called java.lang.ArithmeticException
Below is the Error Thrown :
1 2 |
Exception in thread "main" java.lang.ArithmeticException: / by zero at ArithmeticExceptionExample.main(ArithmeticExceptionExample.java:4) |
3. Less Space or Insufficient Space Memory Error
Below is an example of java.lang.OutOfMemoryError, which occurs when the user is trying to initialize an Integer array with a very large size, and due to the Java heap being insufficient to allocate this memory space, it throws an Error java.lang.OutOfMemoryError: Java heap space
1 2 3 4 5 6 7 8 9 |
public class OutOfMemory { public static void main(String[] args) { Integer[] myArray = new Integer[1000*1000*1000]; } } |
Error :
1 2 |
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at OutOfMemory.main(OutOfMemory.java:5) |
4. Conversion of an Invalid string into a Number
Below is an example of java.lang.NumberFormatException, occurs when the user is trying to convert an alphanumeric string to an integer which leads to java.lang.NumberFormatException
1 2 3 4 5 6 7 8 9 |
public class NumberFormatException { public static void main(String[] args) { int a; a= Integer.parseInt("12Mehtab"); System.out.println(a); } } |
Error :
1 2 3 4 5 |
Exception in thread "main" java.lang.NumberFormatException: For input string: "12Mehtab" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at NumberFormatException.main(NumberFormatException.java:6) |
5. Attempting to Store an Incompatible Value to a Collection
Below is an example where user has created the ArrayList of String but trying to store the integer value which leads to Exception java.lang.Error: Unresolved compilation problem
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.ArrayList; public class IncompatibleType { public static void main(String[] args) { ArrayList<String> student = new ArrayList<>(); student.add(1); } } |
Error :
1 2 3 4 |
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method add(int, String) in the type ArrayList<String> is not applicable for the arguments (int) at IncompatibleType.main(IncompatibleType.java:7) |
How to solve Runtime Rrror in Java Programming?
The runtime errors can be solved by using the try catch blocks in Java. Below are the steps to be followed:
- You will need to Surround the statements that are capable of throwing an exception or a runtime error in the try catch blocks.
- The next step is to catch the error.
- Based on the requirements of the court or an application, it is important to take the necessary action.
Like we discussed earlier about the ArithmeticException example, it can be corrected by making the below changes.
1 2 3 4 5 6 7 8 9 10 11 |
public class ArithmeticExceptionExample { public static void main(String[] args) { try { int num1 = 10, num2 = 0; System.out.println("Result: " + num1/num2); } catch (ArithmeticException ae) { System.out.println("Arithmetic Exception - cannot divide by 0"); } System.out.println("Let’s continue the execution..."); } } |
As the code is surrounded in the try catch blocks, the program will continue to execute after the exception is encountered.
Result :
1 2 3 |
Arithmetic Exception - cannot divide by 0 Let’s continue the execution... |
In this way, it is important for you to identify the Runtime errors and also clear them without any hesitation. You can make use of the try catch blocks and many other resolutions which were helped in successful program execution. Also you will be able to track, manage and analyze the errors in real time. So this was all from this tutorial about fixing the 5 most common types of Runtime Errors in Java But still, if you have any queries, feel free to ask in the comment section. And don’t forget to stay tuned with the Tutorials field to learn this type of awesome tutorial. HAPPY CODING.
People Are Also Reading…
- How to Play Mp3 File in Java Tutorial | Simple Steps
- Menu Driven Program in Java Using Switch Case
- Calculator Program in Java Swing/JFrame with Source Code
- Registration Form in Java With Database Connectivity
- How to Create Login Form in Java Swing
- Text to Speech in Java
- How to Create Splash Screen in Java
- Java Button Click Event
- 11 Best WebSites to Learn Java Online for Free