codepleb
codepleb

Reputation: 10571

Why does start() throw an Exception?

Why does the following code declare, that an Exception can be thrown? Though this is how the method should look according to the javadocs, removing the "throws Exception" part won't lead to a compile error. The documentation doesn't mention why it is necessary.

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

Upvotes: 2

Views: 2156

Answers (1)

James_D
James_D

Reputation: 209225

It's not necessary in the example code you posted. As you observed, the abstract method declared in the Application class declares that it may throw an Exception. This means

  1. it's legal to implement that method and declare that the overridden method may throw an exception
  2. anyone calling Application.start(...) must be prepared to catch the exception

The second point becomes important, because the method is called by the JavaFX framework, typically at startup or via a call to launch(...). So you are guaranteed that the JavaFX framework must handle any exception that is throw from your implementation of the start(...) method.

In the code you posted, nothing there can throw an exception, so you can readily remove the throws clause. However, it becomes useful if, for example, you use 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(...);

    // ...
}

This would not compile if you didn't have throws Exception in the start method (or at least throws IOException); in turn that wouldn't compile if the abstract method in Application didn't declare it may throw an Exception.

Upvotes: 4

Related Questions