Java NumberFormatException
Catch NumberFormatException around the conversion that can fail. This lets a ticket counter explain the bad entry and continue with the next one.
A simple example
NumberFormatException
- Start with Text "x"
- Do this Parse as a whole decimal number
- Result Invalid integer
Syntax
try { int quantity = Integer.parseInt(text); }
catch (NumberFormatException invalid) { /* ask for a whole number */ }
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaHandle three ticket requests
A booking or stock form receives text where the program expects a quantity. Decide what to do with missing, malformed or out-of-range input before using the parsed value in a transaction.
public class Main {
public static void main(String[] args) throws Exception {
for (String input : new String[]{"2", "two", "0"}) {
try {
int count = Integer.parseInt(input);
System.out.println(count > 0 ? "Tickets: " + count : "Choose at least one ticket");
} catch (NumberFormatException invalid) {
System.out.println("Enter a whole number");
}
}
}
}
Tickets: 2 Enter a whole number Choose at least one ticket
The word two fails during parsing. Zero parses successfully, then fails the positive-quantity rule. The counter gives a different response in each case.
Distinguish an oversized ticket request
An events office imports reservation counts from a spreadsheet. One cell contains digits only but exceeds the range of an int, so the importer must flag the request before allocating seats.
class Main {
public static void main(String[] args) throws Exception {
try {
System.out.println(Integer.parseInt("3000000000"));
} catch (NumberFormatException outside) {
System.out.println("Review the ticket count");
}
}
}
Review the ticket count
The digits form a whole number, but its value lies above Integer.MAX_VALUE.
Read a donation total
The library has a signed-off box count written as decimal digits. Parse the entire quantity as a base-ten integer. Let the clerk correct a rejected record.
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 {
Integer.parseInt("24");
System.out.println("Quantity accepted");
} catch (NumberFormatException problem) {
System.out.println("Review quantity");
}
}
}
Quantity accepted
What to watch for
A valid integer can still be outside the range your application allows. Check that rule after parsing.