How to Avoid a Division by Zero Exception in Java

In any compiler language, a mathematical calculation where the divisor is zero results in a run-time error. The application will freeze or return an error to the user. For that reason, programmers should check the value of the divisor before performing the division calculation. This is accomplished using a condition statement called "if." The if statement is used to verify a condition before executing a command.

Instructions
  1. Step 1

    Define your variables. In this example, a is divided by b, but only if b is not zero. To define variables, use the following code:
    int a = 1;
    int b = 0;
    int results = 0;

  2. Step 2

    Set up the if statement. The following if statement code check the value of b to avoid the "divide by zero" error:
    if (b != 0)
    {
    }

  3. Step 3

    Execute the math within the if statement. The enclosed statements are only executed if b is not zero, so you avoid the "divide by zero" error:
    if (b !=0)
    {
    results = a/b;
    }

Related Posts by Categories

0 comments:

Post a Comment

Blog Archive

Powered by Blogger.