Topics Index

Exceptions >
Siva Nookala - 18 Mar 2016
The best way to handle exception is by preventing it. Since exception causes abnormal termination of programs and they consume lot of resources compared the to the normal code execution.

Let's see how the divide by zero ArithmeticException can be prevented by checking the denominator even before dividing the value.
Distribute Chocolates For Students
class DistributeChocolatesForStudents
    public static void main(String arg[])
        int number_of_students = 5;
        int number_of_chocolates = 15;
        if( number_of_students <= 0 )
            System.out.println("Chocolates can not be distributed since there are no students or negative number of students.");
            int number_of_chocolates_per_student = number_of_chocolates / number_of_students;
            System.out.println("Every student gets " + number_of_chocolates_per_student + " chocolates.");

Every student gets 3 chocolates.


In this program, we are distributing the chocolates among students. If we divide the number of chocolates by number of students, then we can find how many chocolates each student gets. But if there are no students, then we will get a '/ by zero' ArithmeticException. To prevent this we are checking that the number of students is not zero. We are also checking that the number of students can not be less than zero. To perform these two checks we are using the less than or equal (<=) operator.

  • Change the value of variable number_of_students from 5 to 0 and see what will be output.
  • Change the value of variable number_of_students from 5 to -4 and see what will be output.
  • Change the value of variable number_of_students from 5 to 7 and see that the number of chocolates is 2. But 7 * 2 is not 15 but 14. Please note that the extra 1 chocolate is missed due to rounding which occurs when we divide an integer with another integer.
In the above program, the variable number_of_students is the denominator and we are checking that it is not zero or less than zero, before we calculate the number of chocolates per student. This is an example of user-friendly program, which gives the user the information in the way he can understand. It is much better than showing complex messages from exceptions. The input data validation technique demonstrated above is very commonly used to prevent run-time errors in programs.

But there are situations where prevention might not be as easy or it may not be entirely possible or the check performed to see if an exception might occur itself could be time consuming operation. In those cases, we have to fall back to the complex Exception Handling In Java with Example Program process.

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App