Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle parsing numbers with same catch block?

I come across a situation quite often where I need to parse a numerical value (e.g. with Integer.parseInt or Double.parseDouble) and I have multiple values. The problem is that I find myself having to duplicate the exception-handling and it becomes ugly. For instance, take the following code:

double lowVal, mediumVal, highVal;
String lowString = "1.2", mediumString = "null", highString = "7.9";

try {
    lowVal = parseDouble(lowString);
} catch (NumberFormatException NaN) {
    //Don't care, just carry on trying to parse the rest...
}

try {
    mediumVal = parseDouble(mediumString);
} catch (NumberFormatException NaN) {
    //Don't care, just carry on trying to parse the rest...
}

try {
    highVal = parseDouble(highString);
} catch (NumberFormatException NaN) {
    //Don't care, just carry on trying to parse the rest...
}

Is there a good pattern for dealing with this situation?

I don't want to use a single-try catch because I want to continue parsing the rest of the numbers.

I should mention that in this example, the values are not initialized but in actual program code they would be. The assignment should only occur if the string values are parseable.

like image 706
Sina Madani Avatar asked Dec 01 '25 02:12

Sina Madani


1 Answers

just extract a method:

double lowVal, mediumVal, highVal;
String lowString = "1.2", mediumString = "null", highString = "7.9";

lowVal = parseDouble(lowString);
mediumVal = parseDouble(mediumString);
highVal = parseDouble(highString);

double parseDouble(String s) {
    try {
        return Double.parseDouble(s);
    } catch (NumberFormatException e) {
        return Double.NAN;
    } 
}

or

Double lowVal;
Double mediumVal;
Double highVal;
String lowString = "1.2", mediumString = "null", highString = "7.9";

lowVal = parseDouble(lowString);
mediumVal = parseDouble(mediumString);
highVal = parseDouble(highString);

Double parseDouble(String s) {
    try {
        return Double.parseDouble(s);
    } catch (NumberFormatException e) {
        return null;
    } 
}
like image 131
Krzysztof Cichocki Avatar answered Dec 03 '25 10:12

Krzysztof Cichocki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!