Does java have a int.tryparse that doesn’t throw an exception for bad data? [duplicate]

No. You have to make your own like this:

public int tryParseInt(String value, int defaultVal) {
    try {
        return Integer.parseInt(value);
    } catch (NumberFormatException e) {
        return defaultVal;
    }
}

…or

public Integer parseIntOrNull(String value) {
    try {
        return Integer.parseInt(value);
    } catch (NumberFormatException e) {
        return null;
    }
}

Leave a Comment