Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

There is no universal try-catch for division by zero: what happens depends on the programming language and the numeric type. Python integer and floating-point division raises ZeroDivisionError, for example, but JavaScript Number division produces infinity or NaN instead of throwing. When zero is an expected input, check the denominator before dividing; catch a specific exception when the language does throw one and recovery is appropriate.

The basic pattern

For ordinary finite arithmetic, the denominator must not be zero. A pre-check prevents the invalid operation:

if denominator is zero:
    return or report a meaningful error
else:
    result = numerator / denominator

Where the language raises an exception, a handler can recover from it:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
try:
    result = numerator / denominator
catch the specific division-by-zero exception:
    handle the invalid denominator

Code in the try block runs normally until an exception is raised. Control then moves to a matching handler; if none matches, the exception continues propagating. A finally block, where available, runs as control leaves the construct, whether or not an exception occurred. Use it for cleanup, not as a substitute for handling an error. Keep the try block narrow so a parsing, file, or programming error is not mistaken for division by zero. See the Python exception-handling guide and MDN’s guide to JavaScript try…catch for these control-flow principles.

Python: catch ZeroDivisionError

Python’s built-in numeric division and modulo operations raise ZeroDivisionError when the divisor is zero. Catch that type specifically if you choose exception handling:

def safe_divide(numerator, denominator):
    try:
        return numerator / denominator
    except ZeroDivisionError:
        return None

result = safe_divide(10, 0)
if result is None:
    print("Cannot divide by zero.")
else:
    print(result)

Here, None is an explicit failure signal. It is not the only valid choice: a function might instead raise a domain-specific exception or return a result object. Avoid returning 0 unless zero is genuinely the correct meaning in the surrounding application.

For interactive input, parsing errors and a zero denominator are different problems. Catch them separately, and retry only when the user can correct the input:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
while True:
    try:
        numerator = float(input("Numerator: "))
        denominator = float(input("Denominator: "))
    except ValueError:
        print("Enter valid numbers.")
        continue

    if denominator == 0:
        print("The denominator must not be zero.")
        continue

    print(f"Result: {numerator / denominator}")
    break

This version validates zero directly because it is an expected user-input condition. To demonstrate exception handling instead, the division can be wrapped in a narrow try block with except ZeroDivisionError. Python’s exception reference covers division and modulo; its tutorial recommends specific handlers rather than a catch-all.

Python’s decimal.Decimal has configurable signals and traps, so its behavior should not be assumed to match ordinary float division in every context. Depending on the decimal context, division by zero can raise a signal or produce infinity. If the application’s rule is simply “the denominator cannot be zero,” an explicit check is clear:

from decimal import Decimal

def divide_decimal(numerator, denominator):
    denominator = Decimal(denominator)
    if denominator == 0:
        raise ValueError("The denominator must not be zero.")
    return Decimal(numerator) / denominator

See the Python decimal documentation for context and trap behavior.

C#: the numeric type matters

Integer and decimal division by zero can throw DivideByZeroException. For a known invalid argument, validating first is usually simpler than catching and translating the exception:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
static int SafeDivide(int numerator, int denominator)
{
    if (denominator == 0)
        throw new ArgumentException(
            "The denominator must not be zero.", nameof(denominator));

    return numerator / denominator;
}

If the operation is part of a larger recoverable workflow, catch the specific exception at the appropriate boundary. Do not assume that a double division will take that path: C# floating-point division by zero produces infinity or NaN rather than DivideByZeroException. Check the result when non-finite values are not acceptable:

double result = numerator / denominator;

if (double.IsNaN(result) || double.IsInfinity(result))
{
    Console.WriteLine("The result is not finite.");
}

Alternatively, validate denominator == 0.0 before dividing. The .NET DivideByZeroException documentation distinguishes integer and decimal behavior from floating-point behavior.

Java: catch ArithmeticException for integer division

Java integer division by zero throws ArithmeticException. If zero is an invalid argument that can be checked in advance, make that contract explicit:

static int safeDivide(int numerator, int denominator) {
    if (denominator == 0) {
        throw new IllegalArgumentException(
            "The denominator must not be zero");
    }
    return numerator / denominator;
}

If you need to recover from the arithmetic exception instead, catch ArithmeticException around the integer operation and handle or translate it. Do not use that handler as a safeguard for double division: Java floating-point division by zero does not throw a runtime exception. It can produce infinity or NaN, so check the result with Double.isInfinite(result) or Double.isNaN(result) when those values are not valid for your program. The distinction is specified in the Java Language Specification, §15.17.2.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

JavaScript: Number division does not throw

For JavaScript’s ordinary Number type, division by zero yields a numeric special value rather than an exception: a nonzero value divided by positive or negative zero produces positive or negative infinity, while 0 / 0 produces NaN. Consequently, this handler does not catch the ordinary Number case:

try {
  const result = 10 / 0;
  console.log(result); // Infinity
} catch (error) {
  // Not reached for Number division by zero
}

Validate the denominator if zero is disallowed, or check whether the result is finite if that is the rule your application needs:

function safeDivide(numerator, denominator) {
  if (denominator === 0) {
    throw new Error("The denominator must not be zero.");
  }
  return numerator / denominator;
}

function divideIfFinite(numerator, denominator) {
  const result = numerator / denominator;
  if (!Number.isFinite(result)) {
    throw new Error("Division did not produce a finite result.");
  }
  return result;
}

The second check also rejects non-finite inputs or results for reasons other than a zero denominator, so choose it only if “finite result” is the desired contract. JavaScript BigInt behaves differently: division by 0n throws RangeError. You can pre-check it directly:

function safeBigIntDivide(numerator, denominator) {
  if (denominator === 0n) {
    throw new RangeError("The BigInt denominator must not be zero.");
  }
  return numerator / denominator;
}

MDN documents the distinction between JavaScript division and the behavior of try…catch: a handler responds to thrown exceptions, not every undesirable numeric result.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

C: prevent integer division by zero

In C, integer division by zero is undefined behavior, not a portable, ordinary exception that a try/catch handler can recover from. Check before the operation and report failure through the function’s return value or another explicit contract:

#include <stdio.h>

int divide(int numerator, int denominator, int *result)
{
    if (denominator == 0) {
        return 0;  // Failure
    }
    *result = numerator / denominator;
    return 1;      // Success
}

int main(void)
{
    int result;
    if (divide(10, 0, &result)) {
        printf("%dn", result);
    } else {
        printf("Cannot divide by zero.n");
    }
}

A compiler or runtime may appear to report a fault, but portable program logic must not rely on that. Apple’s Xcode division-by-zero guidance likewise recommends checking the divisor. Other languages and libraries may define their own behavior, so verify the rules for the exact language and numeric type you use.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose validation, exception handling, or a result type

Situation Good default
A user may enter zero, or zero is an ordinary invalid argument. Validate before division and prompt again, return a clear error, or reject the argument.
The numeric operation raises a specific exception and recovery belongs at this boundary. Catch that exception narrowly; translate it to a useful domain error if needed.
The numeric type returns infinity or NaN instead of throwing. Validate the denominator or check the result for the values the application disallows.
Failure is expected and callers should be required to handle it. Return an explicit error/result or option type rather than hiding failure in a fallback value.
The language defines the operation as undefined behavior. Prevent the operation with a check; do not depend on exception handling.

Exception handling is for recovery when an operation raises; it does not itself prevent division by zero. When the denominator is visible and zero is a normal possibility, a pre-check makes the rule obvious. A reusable library might return a result/error value or raise a domain-specific exception so callers can decide what to do. For example, a Python function could raise InvalidDenominatorError derived from ValueError, or return {"ok": false, "error": "denominator_must_not_be_zero"}. Pick one documented contract rather than quietly substituting zero, one, or an empty string.

Common mistakes and edge cases

  • Catching too broadly: A broad except Exception or catch (Exception) around parsing, I/O, and division can relabel unrelated failures as division by zero. Catch only the expected exception and let other failures propagate.
  • Using the wrong exception: Java’s ArithmeticException and C#’s DivideByZeroException do not handle infinity from floating-point division. JavaScript Number division does not throw at all.
  • Confusing zero with malformed input: A string that cannot be converted to a number is a parsing or validation failure, not a division-by-zero exception. Handle conversion separately.
  • Assuming all zeros are represented identically: Floating-point formats can represent positive and negative zero. In JavaScript, 1 / +0 is Infinity and 1 / -0 is -Infinity. Ordinary business rules often treat both as zero; numerical work may need to preserve the sign. See MDN’s overview of JavaScript data types and values.
  • Overlooking modulo: Remainder by zero can have the same exception or special-value issue. Python raises ZeroDivisionError for modulo; JavaScript Number remainder by zero yields NaN, while BigInt remainder by zero throws RangeError. See the references for Python exceptions and JavaScript remainder.
  • Mixing up 0 / 0 with 10 / 0: Integer operations may raise the same kind of arithmetic exception, while floating-point arithmetic commonly yields NaN for zero divided by zero and infinity for a nonzero value divided by zero.
  • Missing other arithmetic limits: A nonzero denominator does not rule out overflow. For example, in some integer types the minimum value divided by -1 is a separate overflow case. Handle it according to the language and type if it matters to the application.
  • Logging too much: Diagnostics should not automatically include raw user input or sensitive values. Log a safe error category and only the context needed to debug.

Test the behavior, not just the handler

Test ordinary success and the exact failure contract for the language and numeric type. A useful minimum set is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Case What to verify
10 / 2 Returns the expected result, 5 or 5.0.
10 / 0 Produces the documented error, special value, or rejection path.
0 / 0 Checks the distinct NaN or exception behavior.
-10 / 2 and 10 / -2 Returns the expected negative result.
Positive and negative floating-point zero Confirms whether the application treats them alike or checks the sign.
Malformed numerator or denominator Shows a parsing/input error rather than a false division error.
Unexpected exception Confirms it is not mislabeled or swallowed by the division handler.
Repeated retry and large values Ensures retries can end and checks overflow or non-finite results where relevant.

For the Python safe_divide function above, if its documented contract is to return None on a zero denominator, simple checks are:

def test_safe_divide():
    assert safe_divide(10, 2) == 5
    assert safe_divide(10, 0) is None
    assert safe_divide(-10, 2) == -5

Also test the interactive or API boundary separately: it should reject or retry zero, report malformed input accurately, and preserve unexpected errors rather than silently returning a plausible-looking answer.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.