为什么 start() 抛出异常?

Why does start() throw an Exception?

为什么以下代码声明可以抛出异常? 虽然根据 javadocs,方法应该是这样的,但删除 "throws Exception" 部分不会导致编译错误。文档没有提到为什么有必要。

public class GUI extends Application {

    public static void main(String... args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        BorderPane bp = new BorderPane();
        Scene scene = new Scene(bp, 640, 480);
        stage.setScene(scene);
        stage.show();
    }
}

您发布的示例代码中没有必要。如您所见,在 Application class 中声明的抽象方法声明它可能会抛出异常。这意味着

  1. 实现该方法并声明被覆盖的方法可能会抛出异常是合法的
  2. 任何调用 Application.start(...) 的人都必须准备好捕获异常

第二点变得很重要,因为该方法由 JavaFX 框架调用,通常在启动时或通过调用 launch(...)。因此,您可以保证 JavaFX 框架必须处理从您的 start(...) 方法实现中抛出的任何异常。

在您发布的代码中,没有任何内容可以引发异常,因此您可以轻松删除 throws 子句。但是,例如,如果您使用 FXML:

,它就会变得有用
@Override
public void start(Stage primaryStage) throws Exception {

    // FXMLLoader.load(...) throws an IOException, no need to handle it here
    // we just let it propagate up and the JavaFX framework will handle it
    Parent root = FXMLLoader.load(...);

    // ...
}

如果在 start 方法中没有 throws Exception(或至少 throws IOException),这将无法编译;反过来,如果 Application 中的抽象方法没有声明它可能会抛出异常,则不会编译。