BackendBench
Coffee

Home โ€บ Java exceptions โ€บ NumberFormatException

Unchecked exception ยท java.lang

NumberFormatException: causes and fixes

A string could not be parsed as a number, usually by Integer.parseInt or Double.parseDouble.

What it looks like

java.lang.NumberFormatException: For input string: "12a"

Extends IllegalArgumentException in java.lang.

What it means

The parse methods of Integer, Long, Double, BigDecimal and friends throw NumberFormatException when the text is not a valid number in the expected format. The message quotes the offending input, which makes empty strings and stray whitespace easy to spot: For input string: "" means the string was empty, and Cannot parse null string means it was null.

Common causes

How to fix it

  1. Trim the input and check for empty before parsing.
  2. Use Long.parseLong or BigInteger when values can exceed the int range.
  3. Use NumberFormat.getInstance(locale) to parse locale-formatted numbers, and BigDecimal for money.
  4. Catch the exception at the boundary where the text enters the system and turn it into a validation error.

Broken and fixed

fails
int qty = Integer.parseInt(request.getParameter("qty")); // null, "" or " 3" fail
works
String raw = request.getParameter("qty");
int qty = (raw == null || raw.isBlank()) ? 1 : Integer.parseInt(raw.trim());

๐Ÿ”Ž Unravel the failing code ๐Ÿ”Ž Unravel the fix

In Spring and enterprise code

In Spring MVC, a bad number in a @RequestParam int becomes a MethodArgumentTypeMismatchException and a 400 response before your code runs.

Debug it faster

Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.

Frequently asked questions

Is NumberFormatException a checked or unchecked exception?

NumberFormatException is an unchecked exception (it extends IllegalArgumentException, which is a RuntimeException), so you are not forced to catch it. Prevent it with validation, or handle it where the input enters the system.

Which package is NumberFormatException in?

It lives in java.lang, so the import is import java.lang.NumberFormatException; (java.lang needs no import).

What is the first thing to check when I see NumberFormatException?

Read the message and the first stack trace line in your own code. The usual causes are: Whitespace, a thousands separator or a currency symbol in the text: " 42", "1,000", "$5"; and An empty or null value from a form field, query parameter or CSV cell.

Related exceptions

More tools you might need