Question

Out of curiosity I tried to create a really large string. It turned out that the Formatter class chokes on width specifications exceeding Integer.MAX_VALUE:

// Produces an empty string. (2147483648 = Integer.MAX_VALUE + 1)
String.format("%2147483648s", "");

So I went off to verify that it was indeed according to spec. But all it says is

If the format specifier contains a width or precision with an invalid value or which is otherwise unsupported, then a IllegalFormatWidthException or IllegalFormatPrecisionException respectively will be thrown.

So in my opinion the correct behavior would be to throw an IllegalFormatWidthException.

Is this bug (?) documented somewhere? (If not, I'll go report it.)


Also, it should be noted that if one puts a - in front of the width (to left-justify the output):

String.format("%-2147483648s", "");

it indeed throws a MissingFormatWidthException (which, as I see it, seems to be correct behavior).

(I'm using OpenJDK version 1.6.0_20.)

Was it helpful?

Solution

I think you're right and that it's a bug: it should throw IllegalFormatWidthException, if any existing exception.

The javadoc for that exception says "Unchecked exception thrown when the format width is a negative value other than -1 or is otherwise unsupported", which oddly doesn't specifically mention values that are too large. I think the "otherwise unsupported" clause makes this a reasonable exception to throw.

OTHER TIPS

The format/formatter documentation should address this case, which is caused by trying to write a string to the format's appender that exceeds the maximum length of a string. If you actually needed to do this, you would have to use a stream.

See String's Maximum length in Java - calling length() method

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top