Can We handle the RuntimeException in java?


A Run time exception or an unchecked exception is the one which occurs at the time of execution. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.

IndexOutOfBoundsException, ArithmeticException, ArrayStoreException and, ClassCastException are the examples of run time exceptions.

Example

In following Java program, we have an array with size 5 and we are trying to access the 6th element, this generates ArrayIndexOutOfBoundsException.

public class ExceptionExample {
   public static void main(String[] args) {
      //Creating an integer array with size 5
      int inpuArray[] = new int[5];
      //Populating the array
      inpuArray[0] = 41;
      inpuArray[1] = 98;
      inpuArray[2] = 43;
      inpuArray[3] = 26;
      inpuArray[4] = 79;
      //Accessing index greater than the size of the array
      System.out.println( inpuArray[6]);
   }
}

Run time exception

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at MyPackage.ExceptionExample.main(ExceptionExample.java:14)

Handling runtime exceptions

You can handle runtime exceptions and avoid abnormal termination but, there is no specific fix for runtime exceptions in Java, depending on the exception, type you need to change the code.

For example, if you need to fix the ArrayIndexOutOfBoundsException in the first program listed above you need to remove/change the line that accesses index positon of the array beyond its size.

public class ExceptionExample {
   public static void main(String[] args) {
      //Creating an integer array with size 5
      int inpuArray[] = new int[5];
      //Populating the array
      inpuArray[0] = 41;
      inpuArray[1] = 98;
      inpuArray[2] = 43;
      inpuArray[3] = 26;
      inpuArray[4] = 79;
      //Accessing index greater than the size of the array
      System.out.println( inpuArray[3]);
   }
}

Output

26

Updated on: 03-Jul-2020

68 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements