HOWTO · Java

How to Solve Divide by Zero Exception in Java

Learn why Java integer division by zero throws ArithmeticException while floating-point division follows IEEE 754, producing Infinity or NaN, and how to handle both safely.

On this page

Java treats integer and floating-point division by zero differently. Integer division throws ArithmeticException; floating-point division follows IEEE 754 and produces signed Infinity for a nonzero numerator or NaN for zero divided by zero. Guard an integer denominator before dividing, and choose deliberately whether your application should reject floating-point zero or handle the resulting special values.

Integer division by zero in Java

For integer types such as int and long, dividing by zero throws ArithmeticException. The same is true of the remainder operator when its integer divisor is zero. If the exception is uncaught, the current execution path stops before statements after the division.

Here is a complete program that calculates a quotient for two whole-number inputs.

public class Main {
  public static void main(String[] args) {
    int numerator = 10;
    int denominator = 2;
    int quotient = numerator / denominator;
    System.out.println("Quotient: " + quotient);
  }
}

The result is an integer, so 10 / 2 produces 5. If you change denominator to 0, the division throws ArithmeticException; the following print statement is not reached. The exact stack trace includes source-location details that depend on how the program is compiled and run.

Prevent integer division by zero with a conditional

When zero is not a valid divisor for the task, check it before performing the operation and choose a response that fits the application. The example below uses fixed values so it can be compiled and run as one file; replace them with validated input in an application.

public class Main {
  public static void main(String[] args) {
    int numerator = 10;
    int denominator = 0;

    if (denominator == 0) {
      System.out.println("Cannot calculate a quotient: denominator is zero.");
    } else {
      int quotient = numerator / denominator;
      System.out.println("Quotient: " + quotient);
    }
  }
}

The division appears only in the branch where the denominator is nonzero. For user input, validate parsing separately and report the problem in the form your program uses, such as a prompt to enter another value or a validation message in a user interface.

Handle integer division by zero with try-catch

A try-catch block is useful when an integer division is part of a larger operation that can fail and the caller has a meaningful recovery action. Catch ArithmeticException close to the operation when you can respond usefully; a guard is often clearer when zero is an expected input condition.

public class Main {
  public static void main(String[] args) {
    int numerator = 10;
    int denominator = 0;

    try {
      int quotient = numerator / denominator;
      System.out.println("Quotient: " + quotient);
    } catch (ArithmeticException error) {
      System.out.println("Cannot calculate a quotient: denominator is zero.");
    }
  }
}

This catches the integer division failure and lets the program continue after the catch block. It handles the failure after the operation is attempted; it does not make division by zero valid. Avoid a broad catch that hides unrelated programming errors.

Handle integer division by zero with the ternary operator

A ternary expression can keep a short choice near the calculation. Make the fallback explicit: returning 0 may be appropriate for a particular domain, but it can also be mistaken for a real quotient. Use a richer result or a separate conditional when the caller must distinguish failure from a numeric result.

public class Main {
  public static void main(String[] args) {
    int numerator = 10;
    int denominator = 0;

    String result = denominator == 0
        ? "No quotient: denominator is zero."
        : Integer.toString(numerator / denominator);
    System.out.println(result);
  }
}

Java evaluates only the selected branch, so the division is skipped when the denominator is zero. This example uses a message instead of a numeric default to keep the two outcomes distinct.

Floating-point division by zero in Java

Java float and double division follow IEEE 754. Dividing a nonzero value by positive or negative zero produces signed Infinity; the sign depends on both operands. Dividing zero by zero produces NaN (Not a Number). These operations do not themselves throw ArithmeticException.

public class Main {
  public static void main(String[] args) {
    double positiveInfinity = 1.0 / 0.0;
    double negativeInfinity = 1.0 / -0.0;
    double notANumber = 0.0 / 0.0;

    System.out.println("Positive divisor sign: " + positiveInfinity);
    System.out.println("Negative divisor sign: " + negativeInfinity);
    System.out.println("Zero divided by zero: " + notANumber);
  }
}

Infinity and NaN are different values with different meanings. A later calculation involving them may also produce a non-finite result. Check with Double.isFinite(value) or the corresponding Float.isFinite(value) when your application requires a finite number; comparisons such as value == Double.NaN do not detect NaN.

Check floating-point denominators with a conditional

If the application defines either signed zero as an unacceptable denominator, compare the value with 0.0 before dividing. Java considers positive and negative zero equal in this comparison. An exact-zero check does not address every near-zero numerical stability concern; the acceptable range depends on the scale and meaning of your data.

public class Main {
  public static void main(String[] args) {
    double numerator = 10.0;
    double denominator = 0.0;

    if (denominator == 0.0) {
      System.out.println("Cannot calculate a quotient: denominator is zero.");
    } else {
      double quotient = numerator / denominator;
      System.out.println("Quotient: " + quotient);
    }
  }
}

Use a tolerance only when the domain calls for one, and choose it relative to the magnitude and units of the values. After division, validate the result with Double.isFinite if Infinity or NaN is not acceptable downstream.

Raise and catch an application-defined exception for floating-point zero

Floating-point division by zero does not throw ArithmeticException, so a try-catch around the division alone will not reject a zero denominator. If your API represents this condition as an error, check explicitly and throw an application-defined exception before dividing. The example uses IllegalArgumentException because the supplied argument is outside the method’s accepted inputs.

public class Main {
  static double divide(double numerator, double denominator) {
    if (denominator == 0.0) {
      throw new IllegalArgumentException("Denominator must not be zero.");
    }
    return numerator / denominator;
  }

  public static void main(String[] args) {
    try {
      System.out.println("Quotient: " + divide(10.0, 0.0));
    } catch (IllegalArgumentException error) {
      System.out.println("Cannot calculate a quotient: " + error.getMessage());
    }
  }
}

The explicit check creates the exception; the division operation does not. If zero is valid in your domain, do not reject it this way. Instead, handle the resulting Infinity or NaN according to the application’s requirements.

Choose a fallback for floating-point zero with the ternary operator

Use a ternary expression for a compact policy choice when the fallback is clear to the caller. Here, a message represents the no-quotient case; it avoids presenting 0.0 as though it were the mathematical result of division by zero.

public class Main {
  public static void main(String[] args) {
    double numerator = 10.0;
    double denominator = 0.0;

    String result = denominator == 0.0
        ? "No quotient: denominator is zero."
        : Double.toString(numerator / denominator);
    System.out.println(result);
  }
}

If the method must return a number, select a fallback only when the domain defines what it means, and provide another way for callers to identify that fallback. Otherwise, preserve the IEEE 754 result and validate it where non-finite values are not allowed.

Conclusion

For integer division, guard a zero divisor when it is an expected input condition, or catch ArithmeticException when exception handling is appropriate for the surrounding operation. For floating-point division, Java follows IEEE 754: nonzero values divided by signed zero yield signed Infinity, while zero divided by zero yields NaN.

Choose a response that preserves meaning. Validate floating-point inputs when zero is not allowed, and check for non-finite results when later calculations require finite values. A ternary fallback is concise, but its meaning should be explicit to the code that uses it.