Library contents

Java ArithmeticException

Integer division by zero throws ArithmeticException. A denominator of zero is possible even when the original registration had students.

A simple example

ArithmeticException

  1. Start with 4 divided into zero groups
  2. Do this Attempt integer division or check the divisor
  3. Result Division cannot proceed
A divisor of zero has no valid integer quotient. A guard or handler can select a fallback.

Syntax

Java syntax
fee / students
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Split an equipment fee across a class

A training center shares a fixed equipment fee among the students registered for a workshop. When the last student cancels, the fee calculator should show a message before it divides by the headcount.

From the programint fee = 120
ResultNo students registered
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        int fee = 120;
        int students = 0;
        try {
            System.out.println(fee / students);
        } catch (ArithmeticException emptyClass) {
            System.out.println("No students registered");
        }
    }
}
Output
No students registered

Dividing an integer fee by zero fails before any share is calculated. At a form boundary, checking the headcount first is simpler.

Advertisements

Split a workshop charge after registration

A librarian orders a single tool kit for a group of four. The registration software checks the headcount before it calculates each student's equal share in whole currency units.

From the programint students = 4
Result30
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        int students = 4;
        int fee = 120;
        if (students > 0) System.out.println(fee / students);
    }
}
Output
30

For these inputs the fee is exactly divisible. A real billing policy must also decide how to distribute any remainder.

Split a studio hire fee

Two groups register for a 24-credit rehearsal. Divide the total among the registered groups using whole-number division. The desk puts the batch on hold if the divisor is zero.

Given24 credits / 2 groups
Worked resultShare calculated
Code and output in Java
Java source
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;

class Main {
    public static void main(String[] args) throws Exception {
        try {
            int groups = 2;
            int share = 24 / groups;
            System.out.println("Share calculated");
        } catch (ArithmeticException problem) {
            System.out.println("Hold batch");
        }
    }
}
Output
Share calculated

What to watch for

Floating-point division follows different rules and can yield infinity or NaN. Use integer inputs for this example.

Documentation for ArithmeticException