Open In App

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.

Example 1:






// Create public class
public class GFG {
  
    public void GreeksForGreeks()
    {
        // throw exception
        throw new Greeks();
    }
  
    public static void main(String[] args)
    {
        try {
            new GFG().GreeksForGreeks();
        }
        // catch exception
        catch (Exception x) {
            System.out.println(
                "example of runtime exception");
        }
    }
}
  
// create subclass and extend RuntimeException class
class Greeks extends RuntimeException {
  
    // create constructor of this class
    public Greeks()
    {
        super();
    }
}

Output
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[5] and we want to access array[6]. This is an ArrayIndexOutOfBoundsException because 6 indexes does not exist in this array.



Example 2:




class GFG {
    public static void main(String[] args)
    {
        // create array of 5 size
        int[] a = new int[] { 1, 2, 3, 4, 5 };
  
        // execute for loop
        for (int i = 0; i < 6; i++) {
            // print the value of array
            System.out.println(a[i]);
        }
    }
}

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at GFG.main(File.java:10)

Article Tags :