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
- Start with 4 divided into zero groups
- Do this Attempt integer division or check the divisor
- Result Division cannot proceed
Syntax
fee / students
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaSplit 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.
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");
}
}
}
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.
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.
class Main {
public static void main(String[] args) throws Exception {
int students = 4;
int fee = 120;
if (students > 0) System.out.println(fee / students);
}
}
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.
Code and output in Java
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");
}
}
}
Share calculated
What to watch for
Floating-point division follows different rules and can yield infinity or NaN. Use integer inputs for this example.