【问题标题】:Why won't this method print the message in the exception parameter?为什么此方法不会在异常参数中打印消息?
【发布时间】:2017-08-26 19:53:05
【问题描述】:

我正在编写一个方法,如果可能的话,它应该将一个字符串转换为一个 int,它会抛出一个消息 not possible 的异常。它抛出异常但不打印消息,这意味着它的行为与我注释掉异常条件的行为相同:

private static int throwsMethod() throws NumberFormatException{
    Scanner s = new Scanner(System.in);

    System.out.println("enter a number");
    String intNumber = s.next();

    Integer wrapperIntNumberConv = Integer.parseInt(intNumber);

    if(!(wrapperIntNumberConv instanceof Integer)){
        throw new NumberFormatException("can't make an int");
    }

    int fullConvertedNumber = (int) wrapperIntNumberConv;
    System.out.println(fullConvertedNumber);
    return fullConvertedNumber;
}

如何在没有 try/catch 块的情况下做到这一点(我正在尝试学习异常,在本练习中,没有 try/catch 块)并让它显示消息?

编辑:azro 提出的建议答案没有解决我的问题的原因是因为没有任何东西可以解决标题中带有 throws someException() 的方法

【问题讨论】:

标签: java exception


【解决方案1】:

异常可能是在这一行抛出的:

Integer wrapperIntNumberConv = Integer.parseInt(intNumber);

因为如果字符串不包含可解析的整数,parseInt 本身就会抛出它。 (Documentation)

所以在这种情况下,程序不会到达您的if

您需要将带有parseInt 的行包装在一个try-catch 块中,以便能够在您的消息中引发异常:

String intNumber = s.next();
try {
    return Integer.parseInt(intNumber);
catch(NumberFormatException e) { // catch system's exception
    // throw new one with your message
    throw new NumberFormatException("can't make an int");
}

或者,您可以在调用parseInt之前检查字符串是否包含数字(可选符号和数字):

String intNumber = s.next();
if (intNumber.matches("-?\\d+")) { // see: regular expressions
    return Integer.parseInt(intNumber);
} else {
    throw new NumberFormatException("can't make an int");
}

【讨论】:

  • try/catch 会是什么样子?
  • @Derry 我现在已将其添加到我的答案中。
【解决方案2】:

我不确定你想要什么:如果抛出 NumberFormatException,它就无法到达打印指令

int fullConvertedNumber = (int) wrapperIntNumberConv;
System.out.println(fullConvertedNumber);
return fullConvertedNumber;

所以不会打印任何消息。

如果你想打印“can't make an int”消息,你可以在抛出异常之前打印它,或者通过 try-catch 在调用者方法中打印它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 2013-11-13
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多