我试过了
Thread.setDefaultUncaughtExceptionHandler...
在 main 中,也在 start(Stage primaryStage) 方法中。它不起作用。
我也试过了
public static void main(String[] args) {
try {
launch(args);
}catch(Throwable t) {
System.out.println(t.getMessage);
}
}
异常堆栈跟踪。
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()
的代码(见下文),您将看到异常被吞没(第 146/147 行),因此默认的未捕获异常处理程序不会能够捕获它们 - 基于那段代码,我认为您没有任何选择,只能在您的可运行程序中包含 try/catch block 。
请注意 this issue has been reported (需要登录 - 注册是免费的)并且应该在 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");
}
}
};
}
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 }
关于JavaFX 2 - 捕获所有运行时异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12318861/