JavaFX 8 (Lombard) global exception handling

前端 未结 2 1816
迷失自我
迷失自我 2021-02-10 09:50

I\'m currently trying to build an application with JavaFX 8, but I can\'t get uncaught exception handling to work. Due to this post (https://bugs.openjdk.java.net/browse/JDK-810

2条回答
  •  离开以前
    2021-02-10 10:50

    As I understand it, there's nothing much to it; you just use the regular uncaught exception handling from java.lang.Thread.

    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;
    
    public class UncaughtExceptionTest extends Application {
    
        @Override
        public void start(Stage primaryStage) {
    
            // start is called on the FX Application Thread, 
            // so Thread.currentThread() is the FX application thread:
            Thread.currentThread().setUncaughtExceptionHandler((thread, throwable) -> {
                System.out.println("Handler caught exception: "+throwable.getMessage());
            });
    
            StackPane root = new StackPane();
            Button button = new Button("Throw exception");
            button.setOnAction(event -> {
                throw new RuntimeException("Boom!") ;
            });
            root.getChildren().add(button);
            Scene scene = new Scene(root, 150, 60);
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

提交回复
热议问题