首页 > 解决方案 > JavaFX 正在工作,但 try-catch-finally 代码不起作用

问题描述

我刚开始上关于异常处理的课程,我不确定我在代码中做错了什么——我的目标是创建一个 UI,询问用户他们拥有多少宠物,并检查输入是否是一个整数。谁能指出什么问题?

我已经尝试对我的消息使用 label.setText(),并且我还更改了我使用的异常(我尝试了 NumberFormat)。

这是我使用的块(这是我第一次遇到EH,所以我觉得这个话题有点混乱)

String value = input.getText();                                  
int intval = 0;
intval = Integer.parseInt(value);
try {
    if (0 >= intval) {
        throw new IllegalArgumentException();
    }
    else 
        throw new InputMismatchException();
}

catch(IllegalArgumentException e)
{
    String outputMessage = "The number must be an integer no less than 0!";
    label1.setText(outputMessage);
}

catch(InputMismatchException i) {
    System.out.println("Please enter an integer.");
    System.out.println("You entered: " + intval);
}

finally
{ 
    System.out.println("You own " + intval + " pets.");
}

我要包括的例外情况是,如果用户输入了另一种数字类型而不是整数,以及用户输入的是负整数而不是正整数或 0。我的代码运行,但 try-catch 块并没有真正起作用.

标签: javaexceptionjavafx

解决方案


看起来这段代码有很多缺陷!首先,如果您将输入作为整数,则您不应该将输入作为字符串,您可以引发 InputMismatchException,您可以通过将输入作为字符串你将无法做到这一点。不要使用 finally 块,因为无论你的代码抛出多少异常,finally 块都会被执行。即使你最后输入了 -1(在执行代码时),它也会显示“你有 -1 个宠物:”消息,因为不管发生什么,finally 块都会被执行!我重构了代码以使其以相同的方式工作

Scanner input = new Scanner(System.in);

        boolean exceptionHit = false;

        int value = 0;

        try {
            value = input.nextInt();
            if (value <= 0) {
                throw new IllegalArgumentException();
            }
        }
        catch (IllegalArgumentException e) {
            String outputMessage = "The number must be an integer no less than 0!";
            label1.setText(outputMessage);
            exceptionHit = true;

        } catch (InputMismatchException i) {
            System.out.println("Please enter an integer.");
            exceptionHit = true;
        }
        if (exceptionHit == false)
        System.out.println("You have " + value + " pets");

我已删除 finally 块,因此不会每次都显示最后一条消息!我添加了一个布尔值而不是它,如果遇到任何异常,它将设置为 true。


推荐阅读