Search code examples
javathrownumberformatexception

How to print custom message using problematic input string when NumberFormatException


Exception in thread "main" java.lang.NumberFormatException: For input string: "a"

How can I access the input string which is causing NumberFormatException to print a custom error message in this form:

try {
    /* some code which includes many Integer.parseInt(some_string); */
}
catch (NumberFormatException nfe) {
    System.out.println("This is not a number: " + input_string_which_causing_the_error);
}

Then I should get:

This is not a number: a


Solution

  • You can extract it from the exception:

    } catch (NumberFormatException e) {
        System.err.println(e.getMessage().replaceFirst(".*For input string: ", "This is not a number"));
    }