Exceptions: NumberFormatException.getMessage names the exact string that failed to parse

Integer.parseInt and similar methods throw NumberFormatException whose message quotes the offending input verbatim, which is far more useful for debugging than a generic parse failure would be.

Code
String[] inputs = {"42", "12x", "", "  7"};
for (String input : inputs) {
    try {
        System.out.println("Parsed \"" + input + "\" -> " + Integer.parseInt(input));
    } catch (NumberFormatException e) {
        System.out.println("Failed on \"" + input + "\": " + e.getMessage());
    }
}
Output
Parsed "42" -> 42
Failed on "12x": For input string: "12x"
Failed on "": For input string: ""
Failed on "  7": For input string: "  7"
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms