JavaFX 2 – 捕获所有运行时exception

我试过了

Thread.setDefaultUncaughtExceptionHandler... 

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

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

exception堆栈跟踪。

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)

谢谢你的帮助。

如果检查Platform.runLater()的代码(见下文),您将看到吞下exception(第146/117行),因此默认的未捕获exception处理程序将无法捕获它们 – 基于该部分代码,我认为你没有任何选择,只能在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"); } } }; } 

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 } 

某些托管线程(如UI事件处理程序和ExecutorServices)会自行捕获Throwable以避免线程死亡。 只有死亡的线程才会使用此UncaughtExceptionHandler。 如果要捕获抛出的exception,则必须在可抛出这些exception的方法中执行此操作。

如果UI事件处理程序有一种报告exception的方法,那么它将是一种不同的方法。

你的第二个例子将捕获该线程中抛出的exception。 其他线程抛出的exception将捕获该线程。

将EventDispatcher设置为根节点为我工作。

  public class Frame extends Pane { Frame() { setEventDispatcher(new EventDispatcher() { @Override public Event dispatchEvent(Event event, EventDispatchChain chain) { try { return chain.dispatchEvent(event); } catch (final Exception e) { // handle all the exceptions here return null; } } }); } }