From 6a65b76f2ab90cad2c297ff0d9f747ebb982e515 Mon Sep 17 00:00:00 2001 From: Arthur Chan Date: Sat, 9 Dec 2023 14:33:15 +0000 Subject: [PATCH] [LANG-1723]: Throw NumberFormatException instead of IndexOutOfBoundsException in NumberUtils.getMantissa(String, int) (#1145) * [LANG-1723]: Wrap possible IOOBE with NumberFormatException Signed-off-by: Arthur Chan * Fix unit test Signed-off-by: Arthur Chan * Don't change the formatting * Don't change the formatting * Query length once * Less duplication --------- Signed-off-by: Arthur Chan Co-authored-by: Gary Gregory --- .../org/apache/commons/lang3/math/NumberUtils.java | 12 ++++++++---- .../apache/commons/lang3/math/NumberUtilsTest.java | 1 + 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/apache/commons/lang3/math/NumberUtils.java b/src/main/java/org/apache/commons/lang3/math/NumberUtils.java index 03e1b938a..d908e639b 100644 --- a/src/main/java/org/apache/commons/lang3/math/NumberUtils.java +++ b/src/main/java/org/apache/commons/lang3/math/NumberUtils.java @@ -492,12 +492,16 @@ public static Number createNumber(final String str) { * @param str the string representation of the number * @param stopPos the position of the exponent or decimal point * @return mantissa of the given number + * @throws NumberFormatException if no mantissa can be retrieved */ private static String getMantissa(final String str, final int stopPos) { - final char firstChar = str.charAt(0); - final boolean hasSign = firstChar == '-' || firstChar == '+'; - - return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos); + final char firstChar = str.charAt(0); + final boolean hasSign = firstChar == '-' || firstChar == '+'; + final int length = str.length(); + if (length <= (hasSign ? 1 : 0) || length < stopPos) { + throw new NumberFormatException(str + " is not a valid number."); + } + return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos); } /** diff --git a/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java b/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java index 2ce4b9749..2db7878f9 100644 --- a/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java +++ b/src/test/java/org/apache/commons/lang3/math/NumberUtilsTest.java @@ -724,6 +724,7 @@ public void testCreateNumberZero() { @Test public void testInvalidNumber() { assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("E123e.3")); + assertThrows(NumberFormatException.class, () -> NumberUtils.createNumber("-")); } /**