线程“main”中的异常java.lang.NumberFormatException:对于输入字符串:“a”
如何访问导致NumberFormatException以此格式打印自定义错误消息的输入字符串:
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);
}
然后我应该得到:
这不是数字:a
答案 0 :(得分:2)
您可以从例外中提取它:
} catch (NumberFormatException e) {
System.err.println(e.getMessage().replaceFirst(".*For input string: ", "This is not a number"));
}
答案 1 :(得分:0)
您可以尝试这样的事情
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);
}
答案 2 :(得分:0)
应该是直截了当的:
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);
}
答案 3 :(得分:0)
您可以尝试/捕获NumberFormatException,在这种情况下可能会发生这种情况,并通过包含自定义消息的抛出将异常传播到“ main”。
try {
combinationLength = Integer.parseInt(strCombinationLength);
} catch (NumberFormatException e) {
throw new NumberFormatException("The parameter \"combinationLength \" must be a number");
}
主要
try {
//some code
} catch (NumberFormatException e) {
System.out.println(e.getMessage());
}