Skip to content

Change exception type for large array size#8489

Open
ArthurVCristiano wants to merge 1 commit into
google:masterfrom
ArthurVCristiano:patch-3
Open

Change exception type for large array size#8489
ArthurVCristiano wants to merge 1 commit into
google:masterfrom
ArthurVCristiano:patch-3

Conversation

@ArthurVCristiano

Copy link
Copy Markdown

This pull request fixes an inconsistent exception behavior in the
Strings.repeat() method. When the calculated size of the resulting
String causes an integer overflow, the method currently throws an
ArrayIndexOutOfBoundsException. This PR replaces it with an
IllegalArgumentException, accompanied by a descriptive error message.

ArrayIndexOutOfBoundsException is an implementation detail that leaks
internal behavior to the caller. It does not communicate why the
operation failed — it only signals that something went wrong internally.

The Guava API consistently uses IllegalArgumentException to signal
that a caller passed an invalid argument. For example:

  • Preconditions.checkArgument() throws IllegalArgumentException
  • Strings.padStart() throws IllegalArgumentException for negative
    padding sizes

Throwing ArrayIndexOutOfBoundsException in this case breaks that
contract and forces callers to catch an unintuitive low-level exception
when handling large repeat counts.

This fix was identified through an empirical static analysis of
Google Guava across 20 releases (v10.0 to v29.0) using SpotBugs,
which detected a consistent growth in the number of bugs, reaching
851 total in v29.0. This case illustrates how static analysis can
surface semantic inconsistencies beyond traditional bug patterns.

@cpovirk

cpovirk commented Jun 17, 2026

Copy link
Copy Markdown
Member

It's possible that what we should do is copy the JDK precedent of throwing an Error, especially since we encourage users to migrate to the JDK's equivalent method. But I'm not sure that a failed call to repeat really justifies that strong a response (even though of course a call might trigger an Error anyway but requesting a valid but unavailable amount of memory), so it's hard to get too excited about such a change. I also doubt that we'd change the error message except in perhaps the case of matching the JDK (though it probably isn't worth it).

We might have another API or two like this elsewhere in Guava. It probably won't be worth trying to change them, but this general situation is one that we may want to keep in mind for any future similar APIs.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants