Question

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

Was it helpful?

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"));
}

OTHER TIPS

You can try something like this

    String input="abc"; // declare input such that visible to both try and catch
    try {
        int a = Integer.parseInt(input);
    } catch (NumberFormatException e) {
        System.out.println("This is not a number: " + input);
    }

It should be straight forward:

String some_string = "12";//retrieval logic
try {
    int num = Integer.parseInt(some_string);
} catch (NumberFormatException nfe) {
    System.out.println("This is not a number: " + some_string);
}

You can try/catch NumberFormatException where this can occur and propagate exception to "main" with a throw that contains custom message.

try { 
    combinationLength = Integer.parseInt(strCombinationLength);
} catch (NumberFormatException e) {
    throw new NumberFormatException("The parameter \"combinationLength \" must be a number");
}

In the main

try {
    //some code
} catch (NumberFormatException e) {
    System.out.println(e.getMessage());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top