JavaFX 2 - 捕获所有运行时异常

jer*_*ome 11 java exception-handling javafx-2

我试过了

Thread.setDefaultUncaughtExceptionHandler...
Run Code Online (Sandbox Code Playgroud)


在main中,也在start(Stage primaryStage)方法中.它不起作用.
我也试过了

public static void main(String[] args) {
 try {
  launch(args);
 }catch(Throwable t) {
  System.out.println(t.getMessage);
 }
}
Run Code Online (Sandbox Code Playgroud)


异常堆栈跟踪.

at javafx.concurrent.Task $ TaskCallable $ 2.run(Task.java:1251)at com.sun.javafx.application.PlatformImpl $ 3.run(PlatformImpl.java:141)at com.sun.glass.ui.gtk.GtkApplication ._runLoop(Native Method)at com.sun.glass.ui.gtk.GtkApplication $ 1 $ 1.run(GtkApplication.java:56)at java.lang.Thread.run(Thread.java:662)

谢谢你的帮助.

ass*_*ias 16

如果检查代码Platform.runLater()(见下文),您将看到吞下异常(第146/147行),因此默认的未捕获异常处理程序将无法捕获它们 - 基于该段代码,我不知道你认为你有任何选择,但在runnables中包含try/catch块.

请注意,此问题已报告(需要登录 - 注册是免费的),应在Lombard中修复(= Java FX 8.0将于明年与Java 8一起发布).

您也可以创建一个实用程序方法并调用

Platform.runLater(getFxWrapper(yourRunnable));

public static Runnable getFxWrapper(final Runnable r) {
    return new Runnable() {

        @Override
        public void run() {
            try {
                r.run();
            } catch (Exception e) {
                //here you probably want to log something
                System.out.println("Found an exception");
            }
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

代码Platform.runLater:

  120     private static void runLater(final Runnable r, boolean exiting) {
  121         if (!initialized.get()) {
  122             throw new IllegalStateException("Toolkit not initialized");
  123         }
  124 
  125         pendingRunnables.incrementAndGet();
  126         waitForStart();
  127 
  128         if (SystemProperties.isDebug()) {
  129             Toolkit.getToolkit().pauseCurrentThread();
  130         }
  131 
  132         synchronized (runLaterLock) {
  133             if (!exiting && toolkitExit.get()) {
  134                 // Don't schedule a runnable after we have exited the toolkit
  135                 pendingRunnables.decrementAndGet();
  136                 return;
  137             }
  138 
  139             Toolkit.getToolkit().defer(new Runnable() {
  140                 @Override public void run() {
  141                     try {
  142                         r.run();
  143                         pendingRunnables.decrementAndGet();
  144                         checkIdle();
  145                     } catch (Throwable t) {
  146                         System.err.println("Exception in runnable");
  147                         t.printStackTrace();
  148                     }
  149                 }
  150             });
  151         }
  152     }
Run Code Online (Sandbox Code Playgroud)