Runtime errors happen when one thing goes unsuitable within the regular execution of a program. When extreme sufficient, these errors abruptly terminate an software.
To assist programmers each anticipate and get well from runtime errors, the Java programming language defines a particular class named the RuntimeException.
Given their potential to cease an in any other case correctly functioning program lifeless in its tracks, builders ought to grasp Java’s most typical RuntimeExceptions.
Checklist of RuntimeException examples
The ten most typical examples of RuntimeExceptions in Java are:
- ArithmeticException
- NullPointerException
- ClassCastException
- DateTimeException
- ArrayIndexOutOfBoundsException
- NegativeArraySizeException
- ArrayStoreException
- UnsupportedOperationException
- NoSuchElementException
- ConcurrentModificationException
Anticipate the ArtithmeticException
Information manipulation is a main operate of most Java purposes. When information manipulation contains division, builders have to be cautious of division by zero. If zero ever turns into the denominator in a calculation, Java throws an ArithmeticException.
int x = 100;
int y = 0; // denominator is ready to zero
System.out.println( x/y ); // throws ArithmeticException
On this instance, the denominator is explicitly assigned to zero, so it is apparent {that a} divide-by-zero error will happen. If consumer enter units the denominator, the issue is much less predictable. That is why information cleaning is a vital operate of each software.
Negate the NullPointerException
The NullPointerException is a quite common RuntimeException that Java purposes encounter. Any time a developer writes code that invokes a technique on an uninitialized object in Java, a NullPointerException happens.
String information = null;
System.out.println( information.size() ); // throws NullPointerException
On this instance, the developer units the information variable to null, after which invokes the size() technique. The invocation of the size() technique on the null object triggers the NullPointerException.
keep away from this RuntimeException in your Java packages? Initialize each object you create earlier than you employ it, and carry out a null verify on any object that an exterior library passes into your packages.
Conquer the ClassCastException
Java is a strongly typed language. It strictly enforces sort hierarchies, and won’t forged one object to a different except they share a polymorphic relationship.
Within the following code, the try and forged the Date object right into a Timestamp throws a ClassCastException error at runtime.
Date right this moment = new Date();Timestamp time = (Timestamp)right this moment;
Timestamp inherits from Date, so each Timestamp is a particular sort of Date. However polymorphism in Java is unidirectional — a Date will not be essentially a Timestamp. If the forged went in the other way, i.e., a Timestamp forged right into a Date, the Java runtime exception wouldn’t happen.
lengthy seconds = System.currentTimeMillis(); Timestamp time = new Timestamp(seconds); Date right this moment = (Date)time; // this forged works
Defeat the DateTimeException
Information manipulation is a difficult endeavor. Time zones, datelines and inconsistent date codecs may cause Java to throw numerous DateTimeExceptions at runtime.
For instance, the next code compiles, however the LocalDate class’ HourOfDay area will trigger the try and format the date to fail.
LocalDate now = LocalDate.now(); DateTimeFormatter.RFC_1123_DATE_TIME.format(now);
Fortuitously, there are quite a few totally different date codecs from which to decide on. Change to an ISO_DATE on this case and the Java runtime exception goes away.
LocalDate now = LocalDate.now(); DateTimeFormatter.ISO_DATE.format(now);
ArrayIndexOutOfBoundsException instance
An array in Java requires a set measurement. In the event you try so as to add extra parts than the array can accommodate, this can end result within the ArrayIndexOutOfBoundsException. The next code makes an attempt so as to add a component to the sixth index of an array that was constructed to comprise solely 5 parts:
String[] information = new String[5]; information[6] = "Extra Information";
Java applies zero based mostly counting to parts in an array, so index 6 of an array would check with the seventh aspect. Even the next code would set off an ArrayIndexOutOfBoundsException in Java, as index 4 is a reference to an array’s fifth aspect:
String[] information = new String[5]; information[5] = "Extra Information";
The lack of an array to dynamically resize to suit further parts is a typical runtime exception in Java, particularly for builders who’re new to the language.
Nullify the NegativeArraySizeException
Builders should set array measurement to a constructive integer. If a minus signal slips into the array measurement declaration, this throws the NegativeArraySizeException.
String[] information = new String[-5]; // throws Runtime Exception information[1] = "Extra Information";
It is simple to keep away from this Java runtime exception. Do not set an array’s measurement to a unfavorable quantity.
ArrayStoreException defined
The ArrayStoreException shares similarities with the ClassCastException. This Java runtime exception occurs when the unsuitable sort of object is positioned into an array.
Within the instance beneath, a BigInteger array is created, adopted by an try so as to add a Double. The Double doesn’t share a relationship with the BigInteger, so this triggers an ArrayStoreException at runtime.
Quantity[] bigInt = new BigInteger[5]; bigInt[0] = Double.valueOf(12345);
One technique to keep away from this exception is to be extra particular when declaring the array. If the array was declared as a BigInteger sort, Java would flag the issue as a kind mismatch error at compile time, not runtime.
BigInteger[] bigInt = new BigInteger[5]; bigInt[0] = Double.valueOf(12345); // Java compile error
To keep away from the Java RuntimeException utterly, declare the array because the least generic sort, which on this case could be Double.
Unravel the UnsupportedOperationException
Java programmers typically use the Arrays class to morph a Java array right into a extra user-friendly Checklist. Nonetheless, the Checklist that Java returns is read-only. Builders who’re unaware of this reality and attempt to add new parts run into the UnsupportedOperationException. This instance exhibits how this occurs:
Integer[] information = 1,2,3,5,8,13,21; Checklist<Integer> listing = Arrays.asList(information); listing.add(new Integer(0));
It is easy to keep away from this widespread Java runtime exception. Do not add parts to a read-only Checklist.
Knock out the NoSuchElementException
You’ll be able to’t iterate by way of an empty iterator. The next code, which makes an attempt to get the subsequent aspect in an empty HashSet, throws a NoSuchElementException.
Set set = new HashSet(); set.iterator().subsequent(); // Java runtime exception thrown
To repair this Java runtime exception, merely verify that the gathering class will not be empty, and solely proceed if there are parts contained in the iterator.
if (!set.isEmpty()) set.iterator().subsequent();
Appropriate the ConcurrentModificationException
The asList technique of the Arrays class is not the one time a group requires the read-only remedy.
Once you iterate over a listing, the underlying assortment have to be mounted and never up to date. Thus, the add technique throughout the following snippet of code throws a ConcurrentModificationException.
Checklist servers = new ArrayList(); servers.add("Tomcat"); Iterator<String> iterator = servers.iterator(); whereas (iterator.hasNext()) String server = iterator.subsequent(); servers.add("Jetty"); // throws a Runtime Exception
It is unimaginable to anticipate each doable error which may happen in an software. Nonetheless, data of those 10 most typical runtime exceptions in Java will assist make you a extra polished programmer, and your packages simpler and resilient.