The Most Common Java Runtime Errors

Mouad Oumous
The Fresh Writes
Published in
10 min readFeb 25, 2023

Runtime errors occur when a program does not contain any syntax errors but asks the computer to do something that the computer is unable to reliably do. During compilation, the compiler has no technique to detect these kinds of errors. It is the JVM (Java Virtual Machine) that detects it while the program is running.

· StackOverflowError Exception
· OutOfMemoryError Exception
· NegativeArraySizeException
· ArithmeticException
· ArrayIndexOutOfBoundsException
· ArrayStoreException
· UnsupportedOperationException
· NoSuchElementException
· ClassCastException
· DateTimeException
· ConcurrentModificationException
· InputMismatchException
· IllegalFormatConversionException
· NumberFormatException
· InvalidParameterException
· NullPointerException

StackOverflowError Exception

StackOverflowError is an error which Java doesn’t allow to catch, for instance, stack running out of space, as it’s one of the most common runtime errors one can encounter.

The main cause of the StackOverflowError is that we haven’t provided the proper terminating condition to our recursive function or template, which means it will turn into an infinite loop. So this error is thrown when Java runs out of it’s available memory.

// Java program to demonstrate
// infinite recursion error
public class StackOverflowErrorClass {
static int i = 0;
// Method to print numbers
public static int printNumber(int x)
{
i = i + 2;
System.out.println(i);
return i + printNumber(i + 2);
}
public static void main(String[] args)
{
// Recursive call without any
// terminating condition
StackOverflowErrorClass.printNumber(i);
}
}

Runtime Error :

RunTime Error in java code :- Exception in thread “main” java.lang.StackOverflowError
at java.io.PrintStream.write(PrintStream.java:526)
at java.io.PrintStream.print(PrintStream.java:597)
at java.io.PrintStream.println(PrintStream.java:736)
at StackOverflowErrorClass.printNumber(StackOverflowErrorClass.java:13)
at StackOverflowErrorClass.printNumber(StackOverflowErrorClass.java:14)
at StackOverflowErrorClass.printNumber(StackOverflowErrorClass.java:14)
.
.
.

Solution: This is generally caused by an infinite loop or infinite recursion, so looking at those loops and recursive calls is a good place to start.

OutOfMemoryError Exception

Insufficient space/memory error (java.lang.OutOfMemoryError) in threads

A java.lang.OutOfMemoryError is a runtime error in Java which occurs when the Java Virtual Machine (JVM) is unable to allocate an object due to insufficient space in the Java heap. The Java Garbage Collector (GC) cannot free up the space required for a new object, which causes a java.lang.OutOfMemoryError. This error can also be thrown when the native memory is insufficient to support the loading of a Java class.

Here is an example of a thrown due to insufficient Java heap space:

public class OutOfMemoryErrorExample {
public static void main(String[] args) {
Integer[] myArray = new Integer[1000 * 1000 * 1000];
}
}

In this example, an Integer array with a very large size is attempted to be initialized. Because the Java heap is insufficient to allocate this array, it throws a java.lang.OutOfMemoryError : Java heap space

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at OutOfMemoryErrorExample.main(OutOfMemoryErrorExample.java:8)

The previous errors are subclasses of VirtualMachineError class wich is also a subclass of Error class but there’s a whole group of other exceptions that are in this category (runtime errors). They’re always thrown automatically by Java and you don’t need to include them in your exception specifications. Conveniently enough, they’re all grouped together by putting them under a single base class called RuntimeException, which is a perfect example of inheritance: It establishes a family of types that have some characteristics and behaviors in common. Also, you never need to write an exception specification saying that a method might throw a RuntimeException (or any type inherited from RuntimeException), because they are unchecked exceptions. Because they indicate bugs, you don’t usually catch a RuntimeException — it’s dealt with automatically. If you were forced to check for RuntimeExceptions, your code could get too messy. Even though you don’t typically catch RuntimeExceptions, in your own packages you might choose to throw some of the RuntimeExceptions.

NegativeArraySizeException

The NegativeArraySizeException is a runtime exception in Java that occurs when an application attempts to create an array with a negative size. Since the NegativeArraySizeException is an unchecked exception (extends RuntimeException), it does not need to be declared in the throws clause of a method or constructor.

Developers must set array size to a positive integer. If a minus sign slips into the array size declaration, this throws the NegativeArraySizeException.

class JavaError {
public static void main(String[] args) {
int[] arr = new int[-5]; // Negative size of the array
arr[8] = 89;
System.out.println("Something went wrong!");
}
}

Output :

java -cp /tmp/UDRgGsLLQ6 JavaError
Exception in thread "main" java.lang.NegativeArraySizeException: -5
at JavaError.main(JavaError.java:4)

It’s easy to avoid this Java runtime exception. Don’t set an array’s size to a negative number, we get a Negative array size exception when we try to do that.

ArithmeticException

ex. divide by zero errors

Data manipulation is a primary function of most Java applications. When data manipulation includes division, developers must be wary of division by zero. If zero ever becomes the denominator in a calculation, Java throws an ArithmeticException. So we cannot divide anything from zero so when we try to do that we get an arithmetic exception at runtime.

class JavaError {
public static void main(String[] args) {
int a = 23;
int b = 0;
System.out.println(a / b);
}
}

Output :

java -cp /tmp/UDRgGsLLQ6 JavaError
Exception in thread "main" java.lang.ArithmeticException: / by zeroat JavaError.main(JavaError.java:7)

In this example, the denominator is explicitly assigned to zero, so it’s obvious that a divide-by-zero error will occur. If user input sets the denominator, the problem is less predictable. That’s why data cleansing is an important function of every application.

ArrayIndexOutOfBoundsException

when a nonexistent element in an array is accessed

An array in Java requires a set size. If you attempt to add more elements than the array can accommodate, this will result in the ArrayIndexOutOfBoundsException. The following code attempts to add an element to the eight index of an array that was built to contain only five elements:

Accessing array index that does not exists :

class JavaError {
public static void main(String[] args) {
String[] arr = new String[5];
arr[6] = "Hi"; // Accessing array index that does not exsist
System.out.println("Something went wrong!");
}
}

Output :

java -cp /tmp/UDRgGsLLQ6 JavaError
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 5
at JavaError.main(JavaError.java:6)

Explanation :
When we try to access an array index that is out of bounding of the size of the array(in this case it’s 5), we get runtime error of array out of bound.

Java applies zero based counting to elements in an array, so index 6 of an array would refer to the seventh element. Even the following code would trigger an ArrayIndexOutOfBoundsException in Java, as index 4 is a reference to an array’s fifth element:

String[] arr = new String[5];
arr[5] = "Hi"; // Accessing array index that does not exsist

The inability of an array to dynamically resize to fit additional elements is a common runtime exception in Java, especially for developers who are new to the language.

ArrayStoreException

The ArrayStoreException shares similarities with the ClassCastException. This Java runtime exception happens when the wrong type of object is placed into an array.

In the example below, a BigInteger array is created, followed by an attempt to add a Double. The Double does not share a relationship with the BigInteger, so this triggers an ArrayStoreException at runtime.

Number[] bigInt = new BigInteger[5];
bigInt[0] = Double.valueOf(12345);

One way to avoid this exception is to be more specific when declaring the array. If the array was declared as a BigInteger type, Java would flag the problem as a type mismatch error at compile time, not runtime.

BigInteger[] bigInt = new BigInteger[5];
bigInt[0] = Double.valueOf(12345); // Java compile error

To avoid the Java RuntimeException completely, declare the array as the least generic type, which in this case would be Double.

UnsupportedOperationException

Java programmers often use the Arrays class to morph a Java array into a more user-friendly List. However, the List that Java returns is read-only. Developers who are unaware of this fact and try to add new elements run into the UnsupportedOperationException. This example shows how this happens:

Integer[] data = {1,2,3,5,8,13,21};
List<Integer> list = Arrays.asList(data);
list.add(new Integer(0));

It’s simple to avoid this common Java runtime exception. Don’t add elements to a read-only List.

NoSuchElementException

You can’t iterate through an empty iterator. The following code, which attempts to get the next element in an empty HashSet, throws a NoSuchElementException.

Set set = new HashSet();
set.iterator().next(); // Java runtime exception thrown

To fix this Java runtime exception, simply check that the collection class is not empty, and only proceed if there are elements inside the iterator.

if (!set.isEmpty()) {
set.iterator().next();
}

ClassCastException

for data type conversion errors

Java is a strongly typed language. It strictly enforces type hierarchies, and will not cast one object to another unless they share a polymorphic relationship. So ClassCastException happens when you try to wrongly cast an object to a particular class. This means that your object is not an instance or a subclass of this class.

In the following code, the attempt to cast the Date object into a Timestamp throws a ClassCastException error at runtime.

Date today = new Date();Timestamp time = (Timestamp)today;

Timestamp inherits from Date, so every Timestamp is a special type of Date. But polymorphism in Java is unidirectional — a Date is not necessarily a Timestamp. If the cast went in the opposite direction, i.e., a Timestamp cast into a Date, the Java runtime exception would not occur.

long seconds = System.currentTimeMillis();
Timestamp time = new Timestamp(seconds);
Date today = (Date)time; // this cast works

Solution: Look at your class hierarchy and make sure your subclasses inherit properly.

DateTimeException

Data manipulation is a tricky endeavor. Time zones, datelines and inconsistent date formats can cause Java to throw various DateTimeExceptions at runtime.

For example, the following code compiles, but the LocalDate class’ HourOfDay field will cause the attempt to format the date to fail.

LocalDate now = LocalDate.now();
DateTimeFormatter.RFC_1123_DATE_TIME.format(now);

Fortunately, there are numerous different date formats from which to choose. Switch to an ISO_DATE in this case and the Java runtime exception goes away.

LocalDate now = LocalDate.now();
DateTimeFormatter.ISO_DATE.format(now);

ConcurrentModificationException

for incorrectly implemented parallel computations

The asList method of the Arrays class isn’t the only time a collection requires the read-only treatment.

When you iterate over a list, the underlying collection must be fixed and not updated. Thus, the add method within the following snippet of code throws a ConcurrentModificationException.

List servers = new ArrayList();
servers.add("Tomcat");

Iterator<String> iterator = servers.iterator();
while (iterator.hasNext()) {
String server = iterator.next();
servers.add("Jetty"); // throws a Runtime Exception
}

It’s impossible to anticipate every possible error that might occur in an application. However, knowledge of these 10 most common runtime exceptions in Java will help make you a more polished programmer, and your programs more effective and resilient.

InputMismatchException

the InputMismatchException generally occurs when working with Java programs that prompt users for input using the Scanner class. This exception is generally caused during user input when you expect a certain type of input and the user enters in a different type of input. In other words this exception can occur when the input is invalid for the expected type. The input either does not match the pattern for the expected type, or is out of range.

Like passing invalid data e.g. passing a numeric value to the non-numeric field. For example, if a program expects an Integer value for an input but the user enters a String value instead, an InputMismatchException is thrown.

Solution: Wrap the code that asks for user input in a while loop that will continuously prompt the user for correct input.

IllegalFormatConversionException

Explanation: This is associated with printf() and String.format(). It means that there is an unassociated placeholder (too many placeholders, not enough arguments) or it’s the wrong placeholder for the type in the arguments. For example, a %s being a placeholder for an integer will throw this error.

Solution: Make sure the number of placeholders match the number of arguments and make sure the placeholders are the correct type.

NumberFormatException

Attempting to convert an invalid string into a number

The NumberFormatException occurs when an attempt is made to convert a string with improper format into a numeric value. That means, when it is not possible to convert a string in any numeric type (float, int, etc), this exception is thrown. It is a Runtime Exception (Unchecked Exception) in Java. It is a subclass of IllegalArgumentException class.

InvalidParameterException

Passing invalid parameters/arguments to a method

This exception, is a subclass of IllegalArgumentException designed for use by the JCA/JCE engine classes, is thrown when an invalid parameter is passed to a method.

NullPointerException

The NullPointerException is a very common RuntimeException that Java applications encounter. this exception is thrown when Java encounters a null reference when it doesn’t expect one. and a java developer writes code that invokes a method on this reference (uninitialized object).

String data = null;
System.out.println( data.length() ); // throws NullPointerException

In this example, the developer sets the data variable to null, and then invokes the length() method. The invocation of the length() method on the null object triggers the NullPointerException.

To avoid this RuntimeException in your Java programs initialize every object you create before you use it, and perform a null check on any object that an external library passes into your programs.

Do support our publication by following it

--

--

Mouad Oumous
The Fresh Writes

I'm a blogger on medium, l'm a java and kotlin developer, also an Android Developer I mastered various topics such as Networking, UI , UX, Animation ...