Skip to content

fix: Include location info in NumberFormatException from JsonReader#3000

Open
daguimu wants to merge 1 commit intogoogle:mainfrom
daguimu:fix/numberformatexception-location-info-issue1564
Open

fix: Include location info in NumberFormatException from JsonReader#3000
daguimu wants to merge 1 commit intogoogle:mainfrom
daguimu:fix/numberformatexception-location-info-issue1564

Conversation

@daguimu
Copy link
Copy Markdown

@daguimu daguimu commented Mar 26, 2026

Problem

JsonReader.nextDouble(), nextInt(), and nextLong() call Double.parseDouble() on peeked strings. When parsing fails (e.g., for empty strings like ""), the NumberFormatException thrown by Double.parseDouble() contains no JSON location information (line, column, path). This makes it difficult to locate the problematic value in the input JSON.

For example, parsing { x: ''} as an int produces NumberFormatException: empty String with no indication of where in the JSON the error occurred.

Root Cause

The three methods had a comment // don't catch this NumberFormatException. and let the exception from Double.parseDouble() propagate directly. Other NumberFormatException throws in the same methods already include location information via locationString().

Fix

Catch the NumberFormatException from Double.parseDouble() and rethrow with a descriptive message that includes the location string, consistent with other error messages in JsonReader. The message format follows the existing pattern: "Expected a <type> but was <value> at line X column Y path $.<path>".

Tests Added

  • testNextDoubleNumberFormatExceptionContainsLocation — verifies location in path $[0]
  • testNextIntNumberFormatExceptionContainsLocation — verifies location in path $.x
  • testNextLongNumberFormatExceptionContainsLocation — verifies location in path $.y

Impact

Only affects the error path when Double.parseDouble() fails on an invalid numeric string. The exception type (NumberFormatException) is unchanged. All 4589 existing tests pass.

Fixes #1564

JsonReader.nextDouble(), nextInt(), and nextLong() call
Double.parseDouble() on peeked strings, but the NumberFormatException
thrown by parseDouble() contains no JSON location information (line,
column, path), making it difficult to locate the problematic value in
the input.

Catch the NumberFormatException and rethrow with a message that
includes the location string, consistent with other error messages
in JsonReader.

Fixes google#1564
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JsonReader throws NumberFormatException which does not contain location info

1 participant