[NumberFormatException时如何使用有问题的输入字符串打印自定义消息

问题描述 投票:0回答:4

线程“ 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

java throw numberformatexception
4个回答
2
投票
您可以从异常中提取它:

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


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


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


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

© www.soinside.com 2019 - 2024. All rights reserved.