Related Articles

Related Articles

Java Program to Handle the Exception Hierarchies
  • Last Updated : 17 Nov, 2020

Exceptions are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program and terminates the program.

Exception Handling: The process of dealing with exceptions is known as Exception Handling.

Hierarchy of Exceptions: Object class is the parent class of all the classes of java and all the errors or Exceptions objects inherited by throwable class.  The throwable class has two subclass Errors and Exception.

Errors Class: This Class contains those errors which are difficult to handle. They occur during runtime of a program For e.g. StackOverflowError, OutOfMemoryError etc.



  • StackOverflowError: This error occurs due to an inbound condition in the recursion and using an infinite loop in a program. This cause exceeds the stack memory and causes StackOverflowError in the program.

StackOverflowError:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to Handle the exception hierarchies
  
import java.io.*;
  
class GFG {
    static void check(int n)
    {
        if (n == 0) {
            return;
        }
        check(n + 1);
    }
    public static void main(String[] args) { check(3); }
}

chevron_right



Exception class: 

This class contains all the exceptions that can be handled easily There are two subclasses inherited it one is Runtime Exception(unchecked Exception) and checked Exception.

1.Checked exceptions: These exceptions are the subclass of the Exception class. These types of exceptions occur during the compile time of the program by the javac. These exceptions can be handled by the try-catch block otherwise the program will give a compilation error.  ClassNotFoundException, IOException, SQLException etc are the examples of the checked exceptions.

I/O Exception: This Program throw I/O exception because of due FileNotFoundException is a checked exception in Java. Anytime, we want to read a file from the filesystem, Java forces us to handle error situations where the file is not present in the given location.

Assumption: consider myfile.txt file does not exit 

Implementation:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to Handle the exception hierarchies
import java.io.*;
class GFG {
    public static void main(String args[])
    {
        // this file does not exist in the location
        try {
            FileInputStream GFG
                = new FileInputStream("C:/myfile.txt");
        }
        catch (Exception e) {
            System.out.println("File not found");
        }
    }
}

chevron_right


Output

File not found

2. Unchecked Exception



These types of exceptions occur during the runtime of the program.  These are the exceptions that are not checked at a compiled time by the compiler. In Java exceptions under Error and RuntimeException classes are unchecked exceptions, This Exception occurs due to bad programming. Runtime Exceptions like IndexoutOfBoundException, Nullpointer Exception, etc can be handled with the help of Try-Catch Block

(Array)IndexoutOfBoundException: This Exception occurs due to accessing the index greater than and equal to the size of the array length. The program will automatically be terminated after this exception.

Implementation:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to Handle the exception hierarchies
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        int a[] = { 1, 2, 3, 4, 5 };
        try {
            System.out.println(
                a[5]); // accessing the elements of the out
                       // of index of the arrat
        }
        catch (ArrayIndexOutOfBoundsException e) {
            // executes when index out of bound occurs
            System.out.println(
                "Out of index  please check your code");
        }
    }
}

chevron_right


Output

Out of index  please check your code

Multiple Catch Blocks: Sometimes in a program particular code can throw multiple Exceptions object that can be handled using multiple catch blocks under a single try block

Format:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

try {
    // Code where exception can occur
}
catch (ExceptionA e1) {
    // code that executes if Exception of  A occurs
}
catch (ExceptionB e2) {
    // code that executes if Exception of B occurs.
}

chevron_right


Handling ArithmeticException and IndexoutOfBound Exception using Multiple catch blocks.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

import java.io.*;
  
class GFG {
    public static void main (String[] args) {
         try {
      int number[] = new int[10];
      number[10] = 30 / 0;
    } catch (ArithmeticException e) {
      System.out.println("Zero cannot divide any number");
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Index out of size of the array");
    
  }
      
}

chevron_right


Output

Zero cannot divide any number

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :