[英]JavaFX 2 - Catching all runtime exceptions
我試過了
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行),因此默認的未捕獲異常處理程序將無法捕獲它們 - 基於該塊代碼,我認為你沒有任何選擇,只能在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");
}
}
};
}
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。 如果要捕獲拋出的異常,則必須在可拋出這些異常的方法中執行此操作。
如果UI事件處理程序有一種報告異常的方法,那么它將是一種不同的方法。
你的第二個例子將捕獲該線程中拋出的異常。 其他線程拋出的異常將捕獲該線程。
將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;
}
}
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.