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
James_D's answer helped me a lot, but I overlooked his comment. So in case others face the same issue, I post this as a complementary answer.
In my case, my JavaFX app had to face and catch an Out Of Memory Error. For the same code sometimes the OOM appeared on the JavaFX main thread, sometimes not (could be "InvokeLaterDispatcher" thread, "Timer" thread, "process reaper" thread, ...), depending on which thread was first running out of memory. Consequently the error was not always caught and the app didn't always exit as required.
Thus to be sure my app was logging this and exiting, I had to use Thread.setDefaultUncaughtExceptionHandler() as mentioned also by James_D in his comment:
Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
System.out.println(throwable.getClass() + " detected from default UEH.\nWill exit now");
System.exit(1);
});
Now the error is always caught when it appears.
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);
}
}