Problem
I want to convert a java.lang.String
to a java.lang.Integer
, assigning a default value of 0
if the String
is not convertible. Here is what I came up with. I would appreciate an assesment of this approach.
To be honest, it feels a little squirrely to me:
String strCorrectCounter = element.getAttribute("correct");
Integer iCorrectCounter = new Integer(0);
try {
iCorrectCounter = new Integer(strCorrectCounter);
} catch (Exception ignore) { }
Solution
here is a solution :
int tryParseInt(String value) {
try {
return Integer.parseInt(value);
} catch(NumberFormatException nfe) {
// Log exception.
return 0;
}
}
you should catch NumberFormatException instead of exception.
I’d consider using NumberUtils.toInt
from Apache Commons Lang which does exactly this:
public static int NumberUtils.toInt(java.lang.String str, int defaultValue)
The implementation uses the already mentioned Integer.parseInt
with an additional null
check.
See also: Effective Java, 2nd edition, Item 47: Know and use the libraries (The author mentions only the JDK’s built-in libraries but I think the reasoning could be true for other libraries too.)
As others have noted, your code should never catch Exception. Doing so causes all sorts of problems. In addition to the answers given I would also suggest that you don’t default the value to 0 but make it more generic. For example
public static int parseInteger( String string, int defaultValue ) {
try {
return Integer.parseInt(string);
}
catch (NumberFormatException e ) {
return defaultValue;
}
}
You should not use new Integer( string )
instead use Integer.valueOf( string )
. As discussed before in many other threads, valueOf
may be faster due to the fact it can lookup small integer values and reduces the overhead of creating a new object.
Just to be a bit(?) pedantic:
public static final int iDEFAULT_DEFAULT_PARSED_INT = 0;
public static int ifIntFromString( String sToParse) {
return ifIntFromString( sToParse, iDEFAULT_DEFAULT_PARSED_INT );
}
public static int ifIntFromString( String sToParse, int iDefaultValue ) {
int iReturnValue = null;
try {
iReturnValue = Integer.parseInt(sToParse);
} catch ( NumberFormatException e ) {
iReturnValue = iDefaultValue;
}
assert (null != iReturnValue) : "Impossible - no return value has been set!";
return iReturnValue;
}
It would be really great if there were a way to accomplish this without having to catch an exception (due to performance concerns) and without having to write the parsing code yourself – but this is what the base libraries give us.