Reputation: 45
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
Upvotes: 0
Views: 1698
Reputation: 450
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());
}
Upvotes: 0
Reputation: 36339
You can extract it from the exception:
} catch (NumberFormatException e) {
System.err.println(e.getMessage().replaceFirst(".*For input string: ", "This is not a number"));
}
Upvotes: 2
Reputation: 7692
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);
}
Upvotes: 0
Reputation: 35557
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);
}
Upvotes: 0