Java Program to Handle Runtime Exceptions
RuntimeException is the superclass of all classes that exceptions are thrown during the normal operation of the Java VM (Virtual Machine). The RuntimeException and its subclasses are unchecked exceptions. The most common exceptions are NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, InvalidArgumentException etc.
- The NullPointerException is the exception thrown by the JVM when the program tries to call a method on the null object or perform other operations on a null object. A user should not attempt to handle this kind of exception because it will only patch the problem and not completely fix it.
- The ArrayIndexOutOfBoundsException is the exception that is automatically thrown by the JRE(Java Runtime Environment) when a program incorrectly tries to access a certain location in a set that is non-existent. This often happens when the array index requested is negative, or more than or equal to the array’s size. The arrays of Java use the zero-based indexing; thus, the first element of that array has a zero index, the last element comes with an index of size 1, and the nth element comes with an index n-1.
- The InvalidArgumentException is an exception raised when an invalid parameter is passed to a certain method on the server’s referenced connection.
example of runtime exception
Now let’s create one more common example of run time exception called ArrayIndexOutOfBoundsException. This exception occurs when we want to access array more than its size for example we have an array of size 5, array and we want to access array. This is an ArrayIndexOutOfBoundsException because 6 indexes does not exist in this array.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 at GFG.main(File.java:10)