我在Java 6中使用SwingWorker来避免在事件派发线程上运行长时间运行的代码.
如果在我的done()方法中调用get()会返回异常,那么处理异常的适当方法是什么?
我特别关注可能的InterruptedExceptions.JavaDoc示例简单地忽略了异常,但多年来我已经了解到吞咽异常导致难以调试的代码.
示例用法如下:
new SwingWorker<String, Void>() {
@Override
protected String doInBackground() throws Exception {
// do long-running calculation
return result;
}
@Override
protected void done() {
try {
setTextField(get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}.execute();
Run Code Online (Sandbox Code Playgroud) 我通过使用Executor玩SwingWorker的多线程,我在那里错误地从Vector中识别出错误的元素,看起来像这个代码相当忽略了Vector中的元素不存在
我的问题 - >如何/有可能以某种方式捕获此异常
简单的输出
run:
Thread Status with Name :StartShedule, SwingWorker Status is STARTED
Thread Status with Name :StartShedule, SwingWorker Status is DONE
Thread Status with Name :StartShedule, SwingWorker Status is STARTED
Thread Status with Name :StartShedule, SwingWorker Status is DONE
Thread Status with Name :StartShedule, SwingWorker Status is STARTED
Thread Status with Name :StartShedule, SwingWorker Status is DONE
BUILD SUCCESSFUL (total time: 11 seconds)
Run Code Online (Sandbox Code Playgroud)
通过取消注释
//changeTableValues1(); // un-comment for get ArrayIndexOutOfBoundsException
Run Code Online (Sandbox Code Playgroud)
一切都正确,我得到ArrayIndexOutOfBoundsException并输出
run:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: …Run Code Online (Sandbox Code Playgroud)