Skip to content

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

java.lang.NumberFormatException: For input string: "N/A" occurs when you try to parse a string that cannot be converted to a number, such as the string "N/A".

To prevent this exception, you can use a try-catch block to catch the exception and handle it appropriately. For example:


java
try {
    int number = Integer.parseInt("N/A");
} catch (NumberFormatException e) {
    // Handle the exception
}

Alternatively, you can check the input string before trying to parse it, and only attempt to parse it if it is a valid number. For example:


java
String input = "N/A";

if (input.trim().matches("-?\\d+")) {
    int number = Integer.parseInt(input);
} else {
    System.err.println("Invalid input: " + input);
}

This will only attempt to parse the input string if it is a valid integer. Note that Integer.parseInt() throws an exception if the string contains whitespace, so .trim() is used here to ensure the regex validation aligns with the parser's behavior. For more robust parsing (e.g., handling locales or decimal numbers), consider using java.text.NumberFormat.

I hope this helps! Let me know if you have any questions.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.