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

博客讨论了在JavaFX中如何处理Task类中未捕获的异常。由于Platform.runLater()方法会吞掉异常,导致默认的未捕获异常处理器无法工作。作者建议使用try/catch块来包裹Runnable,或者创建一个辅助方法来包装并捕获异常。此外,此问题在JavaFX8中已得到解决。
摘要由CSDN通过智能技术生成

I tried

Thread.setDefaultUncaughtExceptionHandler...

in the main, and also in the start(Stage primaryStage) method. It ain't working.

I also tried

public static void main(String[] args) {

try {

launch(args);

}catch(Throwable t) {

System.out.println(t.getMessage);

}

}

Exception stack trace.

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)

Thanks for helping.

解决方案

If you check the code for Platform.runLater() (see below), you will see that the exceptions are swallowed (lines 146 / 147), so a default uncaught exception handler won't be able to catch them - based on that piece of code, I don't think you have any options but to include try/catch blocks in your runnables.

Note that this issue has been reported (requires login - registration is free) and should be fixed in Lombard (= Java FX 8.0 to be released with Java 8 next year).

You could alternatively create a utility method and call

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 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值