当我已经在方法中抛出错误时出现未处理的异常错误

Unhandled Exception Error when I have already thrown the errors in the method

我正在尝试在为 javafx 中的按钮释放的鼠标上设置鼠标事件。该程序附加到读取按钮数据的 excel 文件。当我使用事件给它一个方法时,它说未处理的错误异常,而我已经在两种方法中都抛出了错误。

@FXML
void initRecipes() throws IOException, InvalidFormatException {

    File file = new File("src/main/resources/RecipeList/Recipes.xlsx");
    String path = file.getAbsolutePath();
    ExcelReader list = new ExcelReader(path);

    int i = 10;
    int sheetNo = 0;

        categories.add(cheap);
        categories.add(showstopper);
        categories.add(quick);
        categories.add(breakfast);
        categories.add(deserts);
        categories.add(salads);

        for (HBox h : categories) {
            for (int k = 0; k < list.getAmount(sheetNo); k++) {

                String buttonId = Integer.toString(i) + Integer.toString(k + 1);
                Button button = new Button(list.getName(buttonId, sheetNo));
                button.setId(buttonId);
                button.setStyle("-fx-background-image: url('" + 
                list.getImage(buttonId, sheetNo) + "')");
                button.setPrefHeight(buttonHeight);
                button.setPrefWidth(buttonWidth);

                button.setOnMouseReleased(event -> changeScene(buttonId));
                 //Error occuring here ^^^^^
                h.getChildren().add(button);
            }

            sheetNo++;
            i += 10;

        }
        list.close();
    }

void changeScene(String buttonId) throws IOException, InvalidFormatException {

    File file = new File("src/main/resources/RecipeList/ingredients.xlsx");
    String path = file.getAbsolutePath();

    ExcelReader list = new ExcelReader(path);

    SecondaryPresenter s = new SecondaryPresenter();
    s.initialize();


}

我非常不确定这是否是设置事件的正确方法,以及如果我已经抛出它说我尚未处理的 2 个错误,为什么它会显示此错误。 有谁知道我做错了什么? 谢谢

EventHandler<T>.handle的签名是

void handle​(T event)

由于您的 changeScene 有一个 throws 子句包含不属于 RuntimeException 的异常,因此 java 编译器确定这些类型的异常未在您的拉姆达表达式。 lambda 表达式产生与以下代码非常相似的结果:

button.setOnMouseReleased(new EventHandler<MouseEvent>() {
    @Override
    public void handle(MouseEvent event) {
        changeScene(buttonId);
    }
});

在上面的代码中应该很容易看出handle方法没有正确处理changeScene抛出的异常。

您需要在 lambda 表达式的正文中添加一个 try/catch

button.setOnMouseReleased(event -> {
    try {
        changeScene(buttonId);
    } catch (IOException | InvalidFormatException ex) {
        // TODO: exception handling
    }
});