From a4bc6c17d71fffe62cd8e478a2e68305df825d40 Mon Sep 17 00:00:00 2001 From: Marcono1234 Date: Mon, 8 Aug 2022 15:39:29 +0200 Subject: [PATCH] Fix JsonTreeReader throwing wrong exception type for non-finite doubles (#1782) Follow-up for #1767 --- .../com/google/gson/internal/bind/JsonTreeReader.java | 2 +- .../gson/internal/bind/JsonElementReaderTest.java | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/gson/src/main/java/com/google/gson/internal/bind/JsonTreeReader.java b/gson/src/main/java/com/google/gson/internal/bind/JsonTreeReader.java index dfa42c48..4cd24e2d 100644 --- a/gson/src/main/java/com/google/gson/internal/bind/JsonTreeReader.java +++ b/gson/src/main/java/com/google/gson/internal/bind/JsonTreeReader.java @@ -213,7 +213,7 @@ public final class JsonTreeReader extends JsonReader { } double result = ((JsonPrimitive) peekStack()).getAsDouble(); if (!isLenient() && (Double.isNaN(result) || Double.isInfinite(result))) { - throw new NumberFormatException("JSON forbids NaN and infinities: " + result); + throw new MalformedJsonException("JSON forbids NaN and infinities: " + result); } popStack(); if (stackSize > 0) { diff --git a/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java b/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java index 204fb3c3..b8e5f623 100644 --- a/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java +++ b/gson/src/test/java/com/google/gson/internal/bind/JsonElementReaderTest.java @@ -20,6 +20,7 @@ import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import com.google.gson.stream.JsonToken; +import com.google.gson.stream.MalformedJsonException; import java.io.IOException; import junit.framework.TestCase; @@ -55,19 +56,22 @@ public final class JsonElementReaderTest extends TestCase { try { reader.nextDouble(); fail(); - } catch (NumberFormatException e) { + } catch (MalformedJsonException e) { + assertEquals("JSON forbids NaN and infinities: NaN", e.getMessage()); } assertEquals("NaN", reader.nextString()); try { reader.nextDouble(); fail(); - } catch (NumberFormatException e) { + } catch (MalformedJsonException e) { + assertEquals("JSON forbids NaN and infinities: -Infinity", e.getMessage()); } assertEquals("-Infinity", reader.nextString()); try { reader.nextDouble(); fail(); - } catch (NumberFormatException e) { + } catch (MalformedJsonException e) { + assertEquals("JSON forbids NaN and infinities: Infinity", e.getMessage()); } assertEquals("Infinity", reader.nextString()); reader.endArray();