Reputation: 10571
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
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
Application.start(...)
must be prepared to catch the exceptionThe 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