If I want to convert a string to int in java, do you know if there is a way to detect overflow?
. , , Integer.parseInt(String s) NumberFormatException , . , Java JDK src.zip. , BigInteger(String s), , , BigInteger . , :
int parseIntWithOverflow(String s) throws Exception {
int result = 0;
try {
result = Integer.parseInt(s);
} catch (Exception e) {
try {
new BigInteger(s);
} catch (Exception e1) {
throw e;
}
throw new NumberFormatException("Input is outside of Integer range!");
}
return result;
}
, Integer.MAX_VALUE, , , @Sergej. , , , :
int result = 0;
try {
result = Integer.parseInt(s);
} catch (NumberFormatException e) {
}