Unchecked Exceptions in JAVA

Unchecked Exceptions in JAVA

Unchecked Exceptions are the exceptions that typically occur due to human, rather than an environmental error. These exceptions are not checked during compile-time, but at runtime, which is the reason they're also called Runtime Exceptions.

For example trying to retrieve an element from the Array. We should check the length of array first before trying to retrieve the element otherwise it might throw ArrayIndexOutOfBoundException at runtime.

Unchecked Exceptions Description
ArithmeticException Arithmetic Error, like divide by zero.
ArrayIndexOutOfBoundsException Accessing an element out of the size of an array or accessing an illegal index.
InputMisMatchException Thrown by Scanner, indicating that the token retrieved does not match the pattern of the expected type.
NullPointerException Trying to access an object reference that has null value or not allocated any space in memory.
NumberFormatException It is thrown by parse methods, when they are unable to convert string into a number.
StringIndexOutOfBoundsException Similar to arrayindexoutofboundsexception, but for an array of strings.

1. ArithmeticException

When an integer is divided by 0.

Program

import java.util.*;
public class DivException
{
    public static void main(String []args){
    Scanner sc = new Scanner(System.in);
    int num,den;
    double ans;
    System.out.println("Enter numerator");
    num = sc.nextInt();
    
    System.out.println("Enter denominator");
    den = sc.nextInt();
        try{
            ans = num/den ;
            System.out.println("Division("+num+"/"+den+") = "+ans);
        }
        catch(ArithmeticException e){
            System.out.println("Cannot divide by zero!");
        }
    }
}

Output

Enter numerator
11
Enter denominator
0
Cannot divide by zero!

In the above program, we can see that when a non zero integer(11 in this case) is divided by 0 an arithmeticexception is thrown.

2. ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsException occurs when you try to access an array index which is beyond the array size or an illegal index . For example, If array is having only 3 elements and we are trying to display 4th element then it would throw this exception.

Program

import java.util.*;
public class ArrayBoundsException
{
    public static void main(String []args){
        Scanner sc = new Scanner(System.in);

        int arr[] = {1,2,3};
        System.out.println("Enter array index to retrieve an element");
        try{
            int index = sc.nextInt();
            int element = arr[index]; 
            System.out.println("Element "+element+" at index "+index);
        }
        catch(ArrayIndexOutOfBoundsException e){
            System.out.println("Trying to access an element beyond size of an array!");
        }
    }
}

Output

Enter array index to retrieve an element
8
Trying to access an element beyond size of an array!

3. InputMismatchException

This exception is thrown by an instance of the Scanner class to indicate that a retrieved token does not match the pattern for the expected type, or that the retrieved token is out of range.

Program

import java.util.*;
public class MismatchException
{
    public static void main(String []args){ 
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter element");
        try{
            int n = sc.nextInt();
            System.out.println("Entered Correctly!");
        }
        catch(InputMismatchException e){
            e.getMessage();
            System.out.println(e+" occurred!");
        }
    }
}

Output

Enter element
a
java.util.InputMismatchException occurred!

In the above program we wanted an integer, but we entered a character, hence inputmismatchexception occurred.

4. NullPointerException

NullPointerException is thrown when program attempts to use an object reference that has the null value.

A nullpointerexception is thrown at runtime whenever your program attempts to use null as if it was a real reference.

Program

public class NullException
{
    public static void main(String []args){
        try{
            String str = null;
            str.length();
        }
        catch(NullPointerException e){
            e.getMessage();
            System.out.println(e+" occurred!");
        }
    }
}

Output

java.lang.NullPointerException occurred!

The length() method, should be used on an object. However in the above example String object str is null so it is not an object due to which NullPointerException occurred.

5. NumberFormatException

NumberFormatException is an unchecked exception thrown by parse() methods when they are unable to convert a string into a number.

This exception occurs when a string is parsed to any numeric variable.

Program

public class NullException
{
    public static void main(String []args){
        try{
            String s = "8";
            int num = Integer.parseInt(s);
            System.out.println(num);         
            String str = "eleven";
            int n = Integer.parseInt(str);
        }
        catch(NumberFormatException e){
            e.getMessage();
            System.out.println(e+" occurred!");
        }
    }
}

Output

8
java.lang.NumberFormatException: For input string: "eleven" occurred!

In the above program int n = Integer.parseInt() would throw NumberFormatException because string "eleven" cannot be parsed to int.

6. StringIndexOutOfBoundsException

This exception is thrown by the methods of the String class, in order to indicate that an index is either negative or greater than the size of the string itself. Moreover, some methods of the String class throw this exception, when the specified index is equal to the size of the string.

Program

public class StringIndexException
{
    public static void main(String []args){
        try{
            String str = "eleven";
            System.out.println("Character at index 3 = "+str.charAt(3));
            str.charAt(8); //Throws Exception
        }
        catch(StringIndexOutOfBoundsException e){
            e.getMessage(); 
            System.out.println(e+" occurred!");
        }
    }
}

Output

Character at index 3 = v
java.lang.StringIndexOutOfBoundsException: String index out of range: 8 occurred!

In the above program, we can see that the length of the string = 6, so if we access try to access an index(8) which is beyond the length of the string, then it will throw StringIndexOfBoundsException.

Share Me!
  •  
  •  
  •  
  •  
  •  
  •