if I want to convert a string into an int in java
do you know if there is a way for me to detect overflow?
by that I mean the string literal actually represents a value which is larger than MAX_INT?
java doc didn’t mention it..
it just says that if the string can not be parsed as an integer, it will through FormatException
didn’t mention a word about overflow..
Yes. Catching parse exceptions would be the correct approach, but the difficulty here is that
Integer.parseInt(String s)throws aNumberFormatExceptionfor any parse error, including overflow. You can verify by looking at the Java source code in the JDK’ssrc.zipfile. Luckily, there exists a constructorBigInteger(String s)that will throw identical parse exceptions, except for range limitation ones, becauseBigIntegers have no bounds. We can use this knowledge to trap the overflow case:If you really need to customize this for only inputs exceeding Integer.MAX_VALUE, you can do that just before throwing the custom exception, by using @Sergej’s suggestion. If above is overkill and you don’t need to isolate the overflow case, just suppress the exception by catching it: