Java Program to Handle Unchecked Exception


Exceptions are the unexpected circumstances occurring during the implementation of the program i.e., at the run time, that interrupt the usual working of the program.

It can occur due to various reasons such as Illegal input given by the user, Failure of the devices, Loss of network connection, Physical limitations, Code faults, trying to open an unavailable file, etc.

There are two major categories of Exceptions  

  • Checked Exception

  • Unchecked Exception

Here, we are going to deal with Unchecked Exception.

The unchecked exception further includes the following −

  • Error class Exception − OutOfMemoryError exception, StackOverflow exception, etc

  • Runtime Exception classes − Nullpointer Exception, IndexoutOfBoundException, etc.

We will learn to deal with the two most common types of exceptions herein. These exceptions are NullpointerException and IndexoutOfBoundException.

IndexoutOfBoundException

This Exception arises when the programmer tries to retrieve the element whose index is greater than or even equal to the size (since the index of an array starts with 0) of the array length. The program is automatically ended as this exception gets encountered.

Example 1

import java.io.*;
public class ExceptionExample1 {
   public static void main(String[] args){
      //creation of an array of length 6 
      int arr[] = { 40, 32, 33, 14, 56, 90 };
      // Trying to retrieve an element greater than
      // index size of the array
      System.out.println(arr[10]);
   }
}

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 6
	at ExceptionExample1.main(ExceptionExample1.java:8)

Example 2

When a user tries to retrieve an array element equal to the index size of an array.

import java.io.*;
public class ExceptionExample1 {
   public static void main(String[] args){
      //creation of an array of length 6
      int arr[] = { 40, 32, 33, 14, 56, 90 };
      // Trying to retrieve an element equal to the
      // index size of the array
      System.out.println(arr[6]);
   }
}

Output

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
	at ExceptionExample1.main(ExceptionExample1.java:8)

Handling ArrayIndexoutOfBoundException

This exception can be handled through a try-catch statement.

A try statement enables programmers to define a block of code to be tested for possible errors and the catch block catches the given exception object and performs the required operations. Thus, the program will execute successfully without being stopped unexpectedly as in the above situation.

Example

import java.io.*;
public class ExceptionExample1 {
   public static void main(String[] args) {
      
      // Filling the array with 6 array elements
      int arr[] = { 40, 32, 33, 14, 56, 90 };
      
      // Try block for exceptions
      try {
         
         // trying to retrieve and print the
         
         // element that is out of the scope of indexes of this array
         System.out.println(arr[10]);
      }
      
      // Catch block to catch the exceptions
      catch (ArrayIndexOutOfBoundsException e) {
         
         // displaying message when index which is not
         
         // present in an array is being accessed
         System.out.println(
         "Array Out of index please rectify your code");
      }
   }
}

Output

Array Out of index please rectify your code

NullPointerException

This exception is encountered when one tries to retrieve the object reference having a null value.

Example

import java.io.*;
public class ExceptionExample2 {
   public static void main(String[] args) {
      // Instance of string str has a null value
      String str = null;
      // Comparison of the null value with the other string
      // throws an exception and prints the same
      System.out.println(str.equals("Hello"));
   }
}

Output

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "" is null
	at ExceptionExample2.main(ExceptionExample2.java:8)

Handling NullPointerException

This exception can also be handled through a try-catch statement.

Example

import java.io.*;
public class ExceptionExample2 {
   public static void main(String[] args) {
      // Assigning NULL value to a string
      String str = null;
      try {
         // Trying to compare the null value with another string
         // and throw an exception
         if (str.equals("Hello")) {
            // print the following string if it is true
            System.out.println("TRUE");
         }
      }
      catch (NullPointerException e) {
         // dealing with the exception
         System.out.println("Object Reference can't be null");
      }
   }
}

Output

Object Reference can't be null

In this tutorial, we discussed Java Program to Handle Unchecked Exception - NullpointerException and IndexoutOfBoundException.

Updated on: 11-Apr-2023

613 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements