This is an automated email from the ASF dual-hosted git repository.

garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-lang.git

commit 8baa3561883e15c65f02ce8ca2f8c61675b6aaf6
Author: Gary Gregory <[email protected]>
AuthorDate: Sun Nov 15 09:40:12 2026 -0500

    Correct Fraction documentation and exception messages
    
    Clarify overflow bounds, parsing exception causes, return values, and
    deserialization validation. Fix inaccurate arithmetic and GCD comments.
    
    Improve three exception messages and add assertions for overflow,
    underflow, and parsing causes. Update changes.xml.
    
    Full Maven validation passes; Fraction retains 100% JaCoCo coverage.
    
    Assisted-By: OpenAI Codex
---
 src/changes/changes.xml                            |  1 +
 .../org/apache/commons/lang3/math/Fraction.java    | 83 +++++++++++-----------
 .../commons/lang3/math/FractionReadObjectTest.java |  7 +-
 .../apache/commons/lang3/math/FractionTest.java    | 52 +++++++++++---
 4 files changed, 87 insertions(+), 56 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index a2810c813..3ddc684fe 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -63,6 +63,7 @@ The <action> type attribute can be add,update,fix,remove.
     <action                   type="fix" dev="ggregory" due-to="Gary 
Gregory">Improve Fraction double-conversion test diagnostics and verify 
preserved ArithmeticException causes for all six unrepresentable-string 
regression cases.</action>
     <action                   type="fix" dev="ggregory" due-to="Gary 
Gregory">Fix premature overflow in Fraction.getFraction(double) and 
decimal-string parsing for representable Integer.MIN_VALUE numerators, with 
boundary tests for every denominator from 1 through 10,000.</action>
     <action                   type="fix" dev="ggregory" due-to="Gary 
Gregory">Complete Fraction coverage for integer-string parsing, negation 
overflow, GCD boundaries, and double-conversion limits; remove redundant 
iteration guards.</action>
+    <action                   type="fix" dev="ggregory" due-to="Gary 
Gregory">Correct Fraction overflow and parsing Javadoc, exception messages, and 
serialization test documentation.</action>
     <!-- ADD -->
     <!-- UPDATE -->
   </release>
diff --git a/src/main/java/org/apache/commons/lang3/math/Fraction.java 
b/src/main/java/org/apache/commons/lang3/math/Fraction.java
index 0ee42c6ab..70eaa2a90 100644
--- a/src/main/java/org/apache/commons/lang3/math/Fraction.java
+++ b/src/main/java/org/apache/commons/lang3/math/Fraction.java
@@ -125,16 +125,15 @@ private static void checkDenominator(final int 
denominator) {
      * </p>
      *
      * @param value The double value to convert
-     * @return A new fraction instance that is close to the value
+     * @return A fraction instance that is close to the value
      * @throws ArithmeticException Thrown if {@code |value| &gt; 
Integer.MAX_VALUE} or {@code value = NaN}.
      * @throws ArithmeticException Thrown if the calculated numerator cannot 
be represented as an {@code int}.
-     * @throws ArithmeticException Thrown if the calculated denominator is 
{@code zero}.
      */
     public static Fraction getFraction(double value) {
         final int sign = value < 0 ? -1 : 1;
         value = Math.abs(value);
         if (value > Integer.MAX_VALUE || Double.isNaN(value)) {
-            throw new ArithmeticException("The value must not be greater than 
Integer.MAX_VALUE or NaN");
+            throw new ArithmeticException("The value must not be NaN and its 
absolute value must not exceed Integer.MAX_VALUE");
         }
         final int wholeNumber = (int) value;
         value -= wholeNumber;
@@ -153,8 +152,8 @@ public static Fraction getFraction(double value) {
         double delta1;
         double delta2 = Double.MAX_VALUE;
         double fraction;
-        // Positive convergent denominators grow at least as fast as Fibonacci 
numbers,
-        // so the denominator bound also bounds the number of iterations.
+        // Convergent denominators grow at least as fast as Fibonacci numbers 
before integer overflow.
+        // Check improvement as well as the denominator: overflow can wrap a 
denominator to a small positive value.
         do {
             delta1 = delta2;
             a2 = (int) (x1 / y1);
@@ -186,8 +185,8 @@ public static Fraction getFraction(double value) {
      * @param numerator   The numerator, for example the three in 'three 
sevenths'
      * @param denominator The denominator, for example the seven in 'three 
sevenths'
      * @return A new fraction instance
-     * @throws ArithmeticException Thrown if the denominator is {@code zero} 
or the denominator is {@code negative} and the numerator is
-     *         {@code Integer#MIN_VALUE}.
+     * @throws ArithmeticException Thrown if the denominator is zero, or if 
the denominator is negative and either argument is
+     *         {@link Integer#MIN_VALUE}, preventing sign normalization 
without overflow.
      */
     public static Fraction getFraction(int numerator, int denominator) {
         checkDenominator(denominator);
@@ -214,7 +213,7 @@ public static Fraction getFraction(int numerator, int 
denominator) {
      * @throws ArithmeticException Thrown if the denominator is {@code zero}.
      * @throws ArithmeticException Thrown if the denominator is negative.
      * @throws ArithmeticException Thrown if the numerator is negative.
-     * @throws ArithmeticException Thrown if the resulting numerator exceeds 
{@code Integer.MAX_VALUE}.
+     * @throws ArithmeticException Thrown if the resulting numerator cannot be 
represented as an {@code int}.
      */
     public static Fraction getFraction(final int whole, final int numerator, 
final int denominator) {
         checkDenominator(denominator);
@@ -231,7 +230,7 @@ public static Fraction getFraction(final int whole, final 
int numerator, final i
             numeratorValue = whole * (long) denominator + numerator;
         }
         if (numeratorValue < Integer.MIN_VALUE || numeratorValue > 
Integer.MAX_VALUE) {
-            throw new ArithmeticException("Numerator too large to represent as 
an Integer.");
+            throw new ArithmeticException("The resulting numerator cannot be 
represented as an int");
         }
         return new Fraction((int) numeratorValue, denominator);
     }
@@ -242,22 +241,19 @@ public static Fraction getFraction(final int whole, final 
int numerator, final i
      * The formats accepted are:
      * </p>
      * <ol>
-     * <li>{@code double} String containing a dot</li>
+     * <li>A string containing a decimal point, parsed by {@link 
Double#parseDouble(String)}</li>
      * <li>{@code "X Y/Z"}</li>
      * <li>{@code "Y/Z"}</li>
      * <li>{@code "X"} (a simple whole number)</li>
      * </ol>
-     * <p>
-     * and a {@code .}
-     * </p>
      *
      * @param str The string to parse, must not be {@code null}
-     * @return The new {@link Fraction} instance
+     * @return The resulting {@link Fraction} instance
      * @throws NullPointerException  Thrown if the string is {@code null}
-     * @throws NumberFormatException Thrown if the number format is invalid, 
or if the string is well-formed but its value cannot be represented as a
-     *                               {@code Fraction}: a zero denominator such 
as {@code "1/0"}, a value outside the range of an {@code int} such as
-     *                               {@code "9999999999.5"}, or a mixed number 
whose combined numerator overflows. For those unrepresentable values, the causal
-     *                               {@link ArithmeticException} is preserved 
as the {@link Throwable#getCause() cause}.
+     * @throws NumberFormatException Thrown if the format is invalid, an 
integer component is outside the range of an {@code int}, or the parsed values
+     *                               cannot form a valid {@code Fraction}. If 
fraction construction throws an {@link ArithmeticException}, for example for
+     *                               a zero denominator or arithmetic 
overflow, that exception is preserved as the {@link Throwable#getCause() cause}.
+     *                               Failures while parsing the numeric 
components do not have an {@code ArithmeticException} cause.
      */
     public static Fraction getFraction(final String str) {
         Objects.requireNonNull(str, "str");
@@ -317,7 +313,7 @@ public static Fraction getFraction(final String str) {
      *
      * @param numerator   The numerator, for example the three in 'three 
sevenths'
      * @param denominator The denominator, for example the seven in 'three 
sevenths'
-     * @return A new fraction instance, with the numerator and denominator 
reduced
+     * @return A fraction instance, with the numerator and denominator reduced
      * @throws ArithmeticException Thrown if the denominator is {@code zero}, 
or the reduced numerator or positive denominator cannot be represented as an
      *                             {@code int}.
      */
@@ -347,8 +343,8 @@ public static Fraction getReducedFraction(int numerator, 
int denominator) {
 
     /**
      * Gets the greatest common divisor of the absolute value of
-     * two numbers, using the "binary gcd" method which avoids
-     * division and modulo operations.  See Knuth 4.5.2 algorithm B.
+     * two numbers, using the "binary gcd" method based on subtraction
+     * and halving. See Knuth 4.5.2 algorithm B.
      * This algorithm is due to Josef Stein (1961).
      *
      * @param u A number
@@ -411,7 +407,7 @@ private static int greatestCommonDivisor(int u, int v) {
             // |u| larger: t positive (replace u)
             // |v| larger: t negative (replace v)
         } while (t != 0);
-        return -u * (1 << k); // gcd is u*2^k
+        return -u * (1 << k); // gcd is -u*2^k
     }
 
     private static int hash(final int value1, final int value2) {
@@ -456,7 +452,7 @@ private static int mulPosAndCheck(final int x, final int y) 
{
      * {@link #getFraction(String)} documents, preserving the original 
exception as the cause.
      *
      * @param str The string being parsed.
-     * @param cause The arithmetic failure: a zero denominator or a value 
outside the range of an {@code int}.
+     * @param cause The arithmetic failure while constructing the fraction.
      * @return The exception for the caller to throw, never {@code null}.
      */
     private static NumberFormatException toNumberFormatException(final String 
str, final ArithmeticException cause) {
@@ -504,7 +500,7 @@ private Fraction(final int numerator, final int 
denominator) {
     }
 
     /**
-     * Gets a fraction that is the positive equivalent of this one.
+     * Gets a fraction that is the non-negative equivalent of this one.
      * <p>
      * More precisely: {@code (fraction &gt;= 0 ? this : -fraction)}
      * </p>
@@ -512,7 +508,8 @@ private Fraction(final int numerator, final int 
denominator) {
      * The returned fraction is not reduced.
      * </p>
      *
-     * @return {@code this} if it is positive, or a new positive fraction 
instance with the opposite signed numerator
+     * @return {@code this} if it is non-negative, or a new positive fraction 
instance with the opposite signed numerator
+     * @throws ArithmeticException Thrown if the numerator is {@link 
Integer#MIN_VALUE} and cannot be negated.
      */
     public Fraction abs() {
         if (numerator >= 0) {
@@ -528,7 +525,7 @@ public Fraction abs() {
      * @param fraction  The fraction to add, must not be {@code null}
      * @return A {@link Fraction} instance with the resulting values
      * @throws NullPointerException Thrown if the fraction is {@code null}.
-     * @throws ArithmeticException Thrown if the resulting numerator or 
denominator exceeds {@code Integer.MAX_VALUE}.
+     * @throws ArithmeticException Thrown if the reduced numerator or positive 
denominator cannot be represented as an {@code int}.
      */
     public Fraction add(final Fraction fraction) {
         return addSub(fraction, true /* add */);
@@ -538,10 +535,10 @@ public Fraction add(final Fraction fraction) {
      * Implements add and subtract using the algorithm described in <a 
href="https://www-cs-faculty.stanford.edu/~knuth/taocp.html";>
      * The Art of Computer Programming (TAOCP)</a> 4.5.1 by Donald Knuth.
      *
-     * @param fraction The fraction to subtract, must not be {@code null}
+     * @param fraction The fraction to add or subtract, must not be {@code 
null}
      * @param isAdd true to add, false to subtract
      * @return A {@link Fraction} instance with the resulting values
-     * @throws IllegalArgumentException Thrown if the fraction is {@code null}.
+     * @throws NullPointerException Thrown if the fraction is {@code null}.
      * @throws ArithmeticException Thrown if the resulting numerator or 
denominator
      *   cannot be represented in an {@code int}.
      */
@@ -574,8 +571,7 @@ private Fraction addSub(final Fraction fraction, final 
boolean isAdd) {
             final long t = isAdd ? Math.addExact(uvp, upv) : 
Math.subtractExact(uvp, upv);
             return new Fraction(Math.toIntExact(t), 
mulPosAndCheck(thisDenominator, thatDenominator));
         }
-        // the quantity 't' requires 65 bits of precision; see knuth 4.5.1
-        // exercise 7. we're going to use a BigInteger.
+        // Compute t exactly before canceling any remaining common factors.
         // t = u(v'/d1) +/- v(u'/d1)
         final BigInteger uvp = 
BigInteger.valueOf(thisNumerator).multiply(BigInteger.valueOf(thatDenominator / 
d1));
         final BigInteger upv = 
BigInteger.valueOf(thatNumerator).multiply(BigInteger.valueOf(thisDenominator / 
d1));
@@ -588,7 +584,7 @@ private Fraction addSub(final Fraction fraction, final 
boolean isAdd) {
         // result is (t/d2) / (u'/d1)(v'/d2)
         final BigInteger w = t.divide(BigInteger.valueOf(d2));
         if (w.bitLength() > 31) {
-            throw new ArithmeticException("overflow: numerator too large after 
multiply");
+            throw new ArithmeticException("overflow: reduced numerator cannot 
be represented as an int");
         }
         return new Fraction(w.intValue(), mulPosAndCheck(thisDenominator / d1, 
thatDenominator / d2));
     }
@@ -717,7 +713,7 @@ public int getNumerator() {
     }
 
     /**
-     * Gets the proper numerator, always positive.
+     * Gets the proper numerator, always non-negative.
      * <p>
      * An improper fraction 7/4 can be resolved into a proper one, 1 3/4. This 
method returns the 3 from the proper fraction.
      * </p>
@@ -726,7 +722,7 @@ public int getNumerator() {
      * If the fraction is negative such as -7/4, it can be resolved into -1 
3/4, so this method returns the positive proper numerator, 3.
      * </p>
      *
-     * @return The numerator fraction part of a proper fraction, always 
positive
+     * @return The numerator fraction part of a proper fraction, always 
non-negative
      */
     public int getProperNumerator() {
         return Math.abs(numerator % denominator);
@@ -739,7 +735,7 @@ public int getProperNumerator() {
      * </p>
      *
      * <p>
-     * If the fraction is negative such as -7/4, it can be resolved into -1 
3/4, so this method returns the positive whole part -1.
+     * If the fraction is negative such as -7/4, it can be resolved into -1 
3/4, so this method returns the signed whole part -1.
      * </p>
      *
      * @return The whole fraction part of a proper fraction, that includes the 
sign
@@ -811,7 +807,7 @@ public long longValue() {
      * @param fraction  The fraction to multiply by, must not be {@code null}
      * @return A {@link Fraction} instance with the resulting values
      * @throws NullPointerException Thrown if the fraction is {@code null}.
-     * @throws ArithmeticException Thrown if the resulting numerator or 
denominator exceeds {@code Integer.MAX_VALUE}.
+     * @throws ArithmeticException Thrown if the reduced numerator or positive 
denominator cannot be represented as an {@code int}.
      */
     public Fraction multiplyBy(final Fraction fraction) {
         Objects.requireNonNull(fraction, "fraction");
@@ -841,6 +837,7 @@ public Fraction multiplyBy(final Fraction fraction) {
      * </p>
      *
      * @return A new fraction instance with the opposite signed numerator
+     * @throws ArithmeticException Thrown if the numerator is {@link 
Integer#MIN_VALUE} and cannot be negated.
      */
     public Fraction negate() {
         // the positive range is one smaller than the negative range of an int.
@@ -859,7 +856,7 @@ public Fraction negate() {
      * </p>
      *
      * @param power The power to raise the fraction to
-     * @return {@code this} if the power is one, {@link #ONE} if the power is 
zero (even if the fraction equals ZERO) or a new fraction instance raised to the
+     * @return {@code this} if the power is one, {@link #ONE} if the power is 
zero (including zero raised to zero), or a fraction instance raised to the
      *         appropriate power
      * @throws ArithmeticException Thrown if this fraction is zero and the 
power is negative.
      * @throws ArithmeticException Thrown if the resulting numerator or 
positive denominator cannot be represented as an {@code int}.
@@ -887,13 +884,13 @@ public Fraction pow(final int power) {
     }
 
     /**
-     * Validates the cached hashCode after deserialization. Throws a {@link 
InvalidObjectException} when the stored hashCode does not match the canonical 
hash
-     * of the deserialized numerator/denominator.
+     * Validates the denominator and cached hash code after deserialization.
      *
-     * @param in See {@link Serializable}.
-     * @throws IOException Thrown as described in {@link Serializable}.
-     * @throws ClassNotFoundException Thrown as described in {@link 
Serializable}.
-     * @throws InvalidObjectException Thrown if the hashCode doesn't match the 
denominator and numerator.
+     * @param in The stream to read.
+     * @throws IOException Thrown if reading the serialized fields fails.
+     * @throws ClassNotFoundException Thrown if a serialized class cannot be 
found.
+     * @throws InvalidObjectException Thrown if the cached hash code does not 
match the denominator and numerator.
+     * @throws ArithmeticException Thrown if the deserialized denominator is 
zero.
      */
     private void readObject(final ObjectInputStream in) throws IOException, 
ClassNotFoundException {
         in.defaultReadObject();
@@ -909,7 +906,7 @@ private void readObject(final ObjectInputStream in) throws 
IOException, ClassNot
      * For example, if this fraction represents 2/4, then the result will be 
1/2.
      * </p>
      *
-     * @return A new reduced fraction instance, or this if no simplification 
possible
+     * @return A reduced fraction instance, or {@code this} if no 
simplification is possible
      */
     public Fraction reduce() {
         if (numerator == 0) {
diff --git 
a/src/test/java/org/apache/commons/lang3/math/FractionReadObjectTest.java 
b/src/test/java/org/apache/commons/lang3/math/FractionReadObjectTest.java
index 62537f818..c8b8a5c48 100644
--- a/src/test/java/org/apache/commons/lang3/math/FractionReadObjectTest.java
+++ b/src/test/java/org/apache/commons/lang3/math/FractionReadObjectTest.java
@@ -35,7 +35,7 @@
 import org.junit.jupiter.api.Test;
 
 /**
- * Tests that a serialized {@link Fraction} can't store a bad cached hashCode.
+ * Tests validation of the denominator and cached hash code when deserializing 
a {@link Fraction}.
  */
 public class FractionReadObjectTest {
 
@@ -62,11 +62,10 @@ public void testBadHashCodeStreamIsRejected() throws 
Exception {
     }
 
     /**
-     * Forged stream: numerator=0, denominator=0, hashCode=hash(0,0). The 
public factory refuses denominator 0 (negative control); readObject does not, 
so the
-     * forged Fraction(0,0) deserializes and divides by zero on {@code 
intValue()}.
+     * Verifies that deserialization rejects a zero denominator even when the 
cached hash code matches the forged fields.
      */
     @Test
-    void testForgedZeroDenominatorDividesByZero() throws Exception {
+    void testForgedZeroDenominatorIsRejected() throws Exception {
         // Negative control: no public factory can build a zero-denominator 
Fraction.
         assertThrows(ArithmeticException.class, () -> Fraction.getFraction(0, 
0));
         final Fraction seed = Fraction.getFraction(1, 2);
diff --git a/src/test/java/org/apache/commons/lang3/math/FractionTest.java 
b/src/test/java/org/apache/commons/lang3/math/FractionTest.java
index 172a8a14a..f07950a67 100644
--- a/src/test/java/org/apache/commons/lang3/math/FractionTest.java
+++ b/src/test/java/org/apache/commons/lang3/math/FractionTest.java
@@ -23,6 +23,7 @@
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertSame;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -50,7 +51,7 @@
  */
 class FractionTest extends AbstractLangTest {
 
-    private static final int SKIP = 500; // 53
+    private static final int SKIP = 500;
 
     private static List<Fraction> arithmeticBoundaryValues() {
         final int[] numerators = {
@@ -74,7 +75,7 @@ private static void assertPowResult(final Fraction fraction, 
final int power) {
             assertThrows(ArithmeticException.class, () -> fraction.pow(power), 
message);
             return;
         }
-        // The providers bound these exponents to keep the exact expected 
values small.
+        // The callers bound these exponents to keep the exact expected values 
small.
         final BigInteger numerator = 
BigInteger.valueOf(fraction.getNumerator()).pow(Math.abs(power));
         final BigInteger denominator = 
BigInteger.valueOf(fraction.getDenominator()).pow(Math.abs(power));
         if (power < 0) {
@@ -274,7 +275,7 @@ void testAdd() {
         final Fraction overflower = f;
         assertThrows(ArithmeticException.class, () -> 
overflower.add(Fraction.ONE)); // should overflow
 
-        // denominator should not be a multiple of 2 or 3 to trigger overflow
+        // The reduced numerator would be one below Integer.MIN_VALUE.
         assertThrows(ArithmeticException.class, () -> 
Fraction.getFraction(Integer.MIN_VALUE, 5).add(Fraction.getFraction(-1, 5)));
 
         final Fraction maxValue = Fraction.getFraction(Integer.MAX_VALUE, 1);
@@ -312,6 +313,16 @@ void testAddBoundaryValues(final Fraction left) {
         }
     }
 
+    @ParameterizedTest(name = "[{index}] add/subtract numerator overflow for 
{0}/3")
+    @ValueSource(ints = {-Integer.MAX_VALUE, Integer.MAX_VALUE})
+    void testAddSubtractOverflowMessages(final int numerator) {
+        final Fraction fraction = Fraction.getFraction(numerator, 3);
+        final ArithmeticException addException = 
assertThrows(ArithmeticException.class, () -> fraction.add(fraction));
+        assertEquals("overflow: reduced numerator cannot be represented as an 
int", addException.getMessage());
+        final ArithmeticException subtractException = 
assertThrows(ArithmeticException.class, () -> 
fraction.subtract(fraction.negate()));
+        assertEquals("overflow: reduced numerator cannot be represented as an 
int", subtractException.getMessage());
+    }
+
     @Test
     void testAddSubtractUnreducedOperands() {
         // 1073741823/2147483646 is 1/2, and 1/2 + 3/5 is 11/10.
@@ -707,12 +718,19 @@ void testFactory_doubleIntegerMinValue(final int 
denominator) {
     }
 
     @ParameterizedTest(name = "[{index}] getFraction({0}) throws")
-    @ValueSource(doubles = {Double.NaN, Double.POSITIVE_INFINITY, 
Double.NEGATIVE_INFINITY, (double) Integer.MAX_VALUE + 1, 2147483646.5d, 
1073741824.5d})
+    @ValueSource(doubles = {2147483646.5d, 1073741824.5d})
     void testFactory_doubleInvalid(final double value) {
         // The fractional boundary values must throw instead of overflowing 
the numerator to a negative value.
         assertThrows(ArithmeticException.class, () -> 
Fraction.getFraction(value));
     }
 
+    @ParameterizedTest(name = "[{index}] getFraction({0}) rejects NaN or 
excessive magnitude")
+    @ValueSource(doubles = {Double.NaN, Double.POSITIVE_INFINITY, 
Double.NEGATIVE_INFINITY, (double) Integer.MAX_VALUE + 1, (double) 
Integer.MIN_VALUE})
+    void testFactory_doubleInvalidMagnitude(final double value) {
+        final ArithmeticException exception = 
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(value));
+        assertEquals("The value must not be NaN and its absolute value must 
not exceed Integer.MAX_VALUE", exception.getMessage());
+    }
+
     @Test
     void testFactory_doubleRoundTrip() {
         Fraction f;
@@ -728,7 +746,7 @@ void testFactory_doubleRoundTrip() {
                 assertEquals(f2.getDenominator(), f.getDenominator(), message);
             }
         }
-        // save time by skipping some tests! (
+        // Sample larger denominators to keep the round-trip test fast.
         for (int i = 1001; i <= 10000; i += SKIP) { // denominator
             for (int j = 1; j <= i; j++) { // numerator
                 final double value = (double) j / (double) i;
@@ -795,6 +813,13 @@ void testFactory_int_int_intInvalid(final int whole, final 
int numerator, final
         assertThrows(ArithmeticException.class, () -> 
Fraction.getFraction(whole, numerator, denominator));
     }
 
+    @ParameterizedTest(name = "[{index}] getFraction({0}, 1, 2) numerator 
overflow")
+    @ValueSource(ints = {Integer.MIN_VALUE, Integer.MAX_VALUE})
+    void testFactory_int_int_intOverflowMessages(final int whole) {
+        final ArithmeticException exception = 
assertThrows(ArithmeticException.class, () -> Fraction.getFraction(whole, 1, 
2));
+        assertEquals("The resulting numerator cannot be represented as an 
int", exception.getMessage());
+    }
+
     @ParameterizedTest(name = "[{index}] getFraction({0}, {1}) throws")
     @CsvSource({
         "1, 0",
@@ -815,6 +840,13 @@ void testFactory_String() {
         assertNullPointerException(() -> Fraction.getFraction(null));
     }
 
+    @ParameterizedTest(name = "[{index}] getFraction({0}) rejects an 
out-of-range integer component")
+    @ValueSource(strings = {"2147483648/1", "1/2147483648", "2147483648 1/2", 
"1 2147483648/2", "1 1/2147483648"})
+    void testFactory_String_componentOverflow(final String value) {
+        final NumberFormatException exception = 
assertThrows(NumberFormatException.class, () -> Fraction.getFraction(value));
+        assertNull(exception.getCause());
+    }
+
     @ParameterizedTest(name = "[{index}] getFraction({0})")
     @CsvSource({
         "'0.0', 0, 1",
@@ -874,7 +906,8 @@ void testFactory_String_integer(final String value, final 
int expectedNumerator)
     @ParameterizedTest(name = "[{index}] getFraction({0}) throws")
     @ValueSource(strings = {"2147483648", "-2147483649", "", "+", "-", "1e3"})
     void testFactory_String_integerInvalid(final String value) {
-        assertThrows(NumberFormatException.class, () -> 
Fraction.getFraction(value));
+        final NumberFormatException exception = 
assertThrows(NumberFormatException.class, () -> Fraction.getFraction(value));
+        assertNull(exception.getCause());
     }
 
     @ParameterizedTest(name = "[{index}] getFraction({0})")
@@ -899,8 +932,8 @@ void testFactory_String_properInvalid(final String value) {
     }
 
     /**
-     * Tests that string contents that are well-formed but unrepresentable 
throw the documented NumberFormatException
-     * (with the ArithmeticException preserved as the cause) instead of an 
undeclared ArithmeticException.
+     * Tests that arithmetic failures during fraction construction are wrapped 
in a NumberFormatException
+     * with the ArithmeticException preserved as the cause.
      *
      * @param value A well-formed string whose value cannot be represented.
      */
@@ -916,6 +949,7 @@ void testFactory_String_properInvalid(final String value) {
     void testFactory_String_unrepresentableThrowsNumberFormatException(final 
String value) {
         final NumberFormatException exception = 
assertThrows(NumberFormatException.class, () -> Fraction.getFraction(value));
         assertInstanceOf(ArithmeticException.class, exception.getCause());
+        assertEquals("The fraction could not be parsed from '" + value + "': " 
+ exception.getCause().getMessage(), exception.getMessage());
     }
 
     @Test
@@ -1514,7 +1548,7 @@ void testSubtract() {
         // Should overflow
         assertThrows(ArithmeticException.class, () -> Fraction.getFraction(1, 
Integer.MAX_VALUE).subtract(Fraction.getFraction(1, Integer.MAX_VALUE - 1)));
 
-        // denominator should not be a multiple of 2 or 3 to trigger overflow
+        // The reduced numerator would be one below Integer.MIN_VALUE.
         assertThrows(ArithmeticException.class, () -> 
Fraction.getFraction(Integer.MIN_VALUE, 5).subtract(Fraction.getFraction(1, 
5)));
 
         assertThrows(ArithmeticException.class, () -> 
Fraction.getFraction(Integer.MIN_VALUE, 1).subtract(Fraction.ONE));

Reply via email to