HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaMajor

Convert String to Integer with default value

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
convertwithvaluedefaultstringinteger

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.

Code Snippets

int tryParseInt(String value) { 
 try {  
     return Integer.parseInt(value);  
  } catch(NumberFormatException nfe) {  
      // Log exception.
      return 0;
  }  
}

Context

StackExchange Code Review Q#19773, answer score: 25

Revisions (0)

No revisions yet.