Java Program to Handle the Exception Methods
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:
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 :
Arithmetic Exception / by zero error.
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.
The catch block with Null Pointer Exception is executed End of program