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 CODE class DistributeChocolatesForStudents OUTPUT Every student gets 3 chocolates. DESCRIPTION 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' THINGS TO TRY
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.
|