Database examples

Fix These 10 Common Examples of RuntimeException in Java

Runtime errors occur when something goes wrong with the normal execution of a program. When severe enough, these errors will abruptly terminate an application.

To help programmers anticipate and recover from runtime errors, the Java programming language defines a special class named Runtime exception.

Given their potential to halt an otherwise properly functioning program, developers should grasp the most common principles of Java. Runtime Exceptions.

List of RuntimeException examples

The 10 most common examples of Runtime Exceptions in Java are:

  1. ArithmeticException
  2. NullPointerException
  3. ClassCastException
  4. DateTimeException
  5. ArrayIndexOutOfBoundsExceptionArrayIndexOutOfBoundsException
  6. NegativeArraySizeExceptionNegativeArraySizeException
  7. ArrayStoreException
  8. UnsupportedOperationExceptionUnsupportedOperationExceptionUnsupportedOperationExceptionUnsupportedOperationExceptionUnsupportedOperationException
  9. NoSuchElementException
  10. ConcurrentModificationExceptionConcurrentModificationException

Anticipating the ArtithmeticException

Data manipulation is a core function of most Java applications. When data manipulation includes division, developers should be wary of division by zero. If ever zero becomes the denominator of a calculation, Java throws a ArithmeticException.

int x = 100;
int y = 0;  // denominator is set to zero
System.out.println( x/y ); // throws ArithmeticException

In this example, the denominator is explicitly assigned to zero, so obviously a divide-by-zero error will occur. If user input defines the denominator, the problem is less predictable. This is why data cleansing is an important function of every application.

Cancel NullPointerException

the NullPointerException is very common Runtime exception encountered by Java applications. Whenever a developer writes code that invokes a method on an uninitialized object in Java, a NullPointerException occurs.

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

In this example, the developer sets the Data variable to badthen invoke the length() method. The summoning of the length() method on the bad the object triggers the NullPointerException.

How to avoid this Runtime exception in your Java programs? Initialize every object you create before using it, and perform null checking on any object that an external library passes to your programs.

Conquer the ClassCast exception

Java is a strongly typed language. It strictly enforces type hierarchies and will not convert one object to another unless they share a polymorphic relationship.

In the following code, the attempt to convert the Dated object in a Timestamp throw a ClassCastException runtime error.

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

Timestamp inherits from Datedso each Timestamp is a special kind of Dated. But polymorphism in Java is unidirectional — a Dated is not necessarily a Timestamp. If the cast went in the opposite direction, i.e. a Timestamp thrown in a Datedthe java runtime exception would not occur.

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

Overcoming the DateTimeException exception

Data manipulation is a tricky business. Inconsistent time zones, dates, and date formats can cause Java to throw various DateTimeExceptions at runtime.

For example, the following code compiles, but the LocalDate to classify’ TimeOfDay 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 many different date formats to choose from. Switch to a ISO_DATE in this case and the Java runtime exception disappears.

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

Exception Example ArrayIndexOutOfBoundsExceptionArrayIndexOutOfBoundsException

An array in Java requires a defined size. If you try to add more elements than the array can hold, it will cause the ArrayIndexOutOfBoundsExceptionArrayIndexOutOfBoundsException. The following code attempts to add an element at the sixth index of an array that was constructed to contain only five elements:

String[] data = new String[5];
data[6] = "More Data";

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

String[] data = new String[5];
data[5] = "More Data";

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

Cancel the NegativeArraySizeException

Developers should set the array size to a positive integer. If a minus sign slips into the array size declaration, this starts the NegativeArraySizeExceptionNegativeArraySizeException.

String[] data = new String[-5]; // throws Runtime Exception
data[1] = "More Data";

It is easy to avoid this Java runtime exception. Do not set the size of an array to a negative number.

ArrayStoreException explained

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

In the example below, a BigInteger array is created, followed by an attempt to add a Double. the Double has no relationship with the BigIntegerso it triggers a 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 BigInteger type, Java would report the problem as a type mismatch error at compile time, not at run time.

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

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

The Java RuntimeException is just one of many types of bugs that can cause a software program to fail.

Untangling the UnsupportedOperationException

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

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

Avoiding this common Java runtime exception is simple. Don’t add items to read-only List.

Remove the NoSuchElementException exception

You cannot loop through an empty iterator. The following code, which tries to get the next item in an empty file HashSetlaunch a NoSuchElementException.

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

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

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

Fix the ConcurrentModificationException

the asList method of Paintings class isn’t the only time a collection requires read-only processing.

When traversing a list, the underlying collection should be fixed and not updated. So the add method in the following code snippet throws a ConcurrentModificationExceptionConcurrentModificationException.

List servers = new ArrayList();
servers.add("Tomcat");
                   
Iterator iterator = servers.iterator();
while (iterator.hasNext()) {
  String server = iterator.next();
  servers.add("Jetty");  // throws a Runtime Exception
}

It is impossible to anticipate all possible errors that may occur in an application. However, knowing these 10 most common runtime exceptions in Java will help you become a more refined programmer and make your programs more efficient and resilient.