Skip to content
Related Articles

Related Articles

Improve Article
Java Program to Handle the Exception Methods
  • Last Updated : 17 Nov, 2020

An unlikely event which disrupts the normal flow of the program is known as an Exception. Java Exception Handling is an object-oriented way to handle exceptions. When an error occurs during the execution of the program, an exception object is created which contains the information about the hierarchy of the Exception and other information which is essential for debugging.

Types of Exceptions:

  • Checked Exceptions
  • Unchecked Exceptions

Handling the Exceptions:

Example 1:

We are asked to distribute chocolates to every class in the school based on the average performance of the class. We are given two arrays of equal length. One array contains the number of chocolates present in each box and the second array contains the number of students in each class. If the average performance of a class is below par, they are not eligible to get any chocolates and the number of chocolates present in the box will be equally distributed among all other boxes. Each class is given one chocolate box respectively. 



So to divide the number of chocolates among the students in a class, we have to divide the number of chocolates by the number of students in the class. Suppose the average performance of a class is below par they wouldn’t get any chocolates and the number of students in that section would be zero. One can face a divide by zero exception while solving the above problem. In order to overcome it, we can use a try-catch block and ask the user to update the information given.

Below is the implementation of the above approach :

Java




// Java program to demonstrate Arithmetic Exception
  
class GFG {
    public static void main(String[] args)
    {
        // Number of chocolates in each box
        int chocolates[] = { 106, 145, 123, 127, 125 };
  
        // Number of students in class
        int students[] = { 35, 40, 0, 34, 60 };
  
        // Number of chocolates given to each student of a
        // particular class
        int numChoc[] = new int[5];
        try {
            for (int i = 0; i < 5; i++) {
                // Calculating the chocolates
                // to be distributed
                numChoc[i] = chocolates[i] / students[i];
            }
        }
        // Catching Divide by Zero Exception
        catch (ArithmeticException error) {
            System.out.println("Arithmetic Exception");
            System.out.println(error.getMessage()
                               + " error.");
        }
    }
}
Output
Arithmetic Exception
/ by zero error.

Example 2:

Java has a robust Error Handling Mechanism that lets us handle multiple Exceptions in one try block using different catch blocks.  Catch blocks in java are like if-else statements that will become active when an exception occurs. When an exception occurs, the program compares the exception object generated to the exception specified in the catch blocks. The program checks the first catch block then moves on to other and so-on until the generated exception is matched. If no catch block is matched, the program halts, and an exception is thrown at the console.

After an Exception is generated in the try block, the control immediately shifts to the catch block, and try block will no longer execute. Tinker with the below code by changing the sizes of the array or changing a particular element in the array2 to zero or initializing the answer array, to get a better understanding of Java Exception Handling.

Below code illustrates how various types of errors can be handled in a single try block. 

Java




// Java Program to Handle Various Exceptions
  
class GFG {
    public static void main(String[] args)
    {
        // Array1 Elements
        int[] array1 = { 2, 4, 6, 7, 8 };
  
        // Array2 Elements
        int[] array2 = { 1, 2, 3, 4, 5 };
        // Initialized to null value
        int[] ans = null;
        try {
            for (int i = 0; i < 5; i++) {
                ans[i] = array1[i] / array2[i];
                // Generates Number Format Exception
                Integer.parseInt("Geeks for Geeks");
            }
        }
        catch (ArithmeticException error) {
            System.out.println(
                "The catch block with Arithmetic Exception is executed");
        }
        catch (NullPointerException error) {
            System.out.println(
                "The catch block with Null Pointer Exception is executed");
        }
        catch (ArrayIndexOutOfBoundsException error) {
            System.out.println(
                "The catch block with Array Index Out Of Bounds Exception is executed");
        }
        catch (NumberFormatException error) {
            System.out.println(
                "The catch block with Number Format Exception is executed");
        }
        // Executes when an exception which
        // is not specified above occurs
        catch (Exception error) {
            System.out.println(
                "An unknown exception is found "
                + error.getMessage());
        }
  
        // Executes after the catch block
        System.out.println("End of program");
    }
}
Output
The catch block with Null Pointer Exception is executed
End of program

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. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :