如何处理Executor执行SwingWorker任务的异常?
无法从 Future 获取 ArrayIndexOutOfBoundsException>如果线程启动 Executor
问题:
如何捕获 ArrayIndexOutOfBoundsException 或由 SwingWorker 执行的 SwingWorker 任务中的任何异常执行器?
答案:
通过在 SwingWorker 的 did() 方法中重新抛出捕获的异常。
详细说明:
使用Executor启动时SwingWorker 任务,该任务在单独的线程上执行。这意味着任务引发的任何异常都不会传播回 SwingWorker 运行的事件调度线程 (EDT)。结果,任务抛出的未捕获异常将被默默吞掉,done() 方法将正常完成。
要捕获并处理任务抛出的异常,可以使用以下步骤:
- 重写SwingWorker中的done()方法。
- 在done()方法中,使用try-catch阻止捕获任务可能抛出的任何异常。
- 使用 ExecutionException 类重新抛出捕获的异常。
通过使用 ExecutionException 重新抛出异常,它将被传播回 EDT,并且可以由任务执行时返回的 Future 上的 get() 方法的调用者处理
示例:
以下代码演示了如何使用上述步骤捕获和处理 Executor 执行的 SwingWorker 任务抛出的异常:
import java.util.concurrent.Executor; import java.util.concurrent.Executors; import javax.swing.SwingWorker; public class TableWithExecutor { private static final Executor executor = Executors.newCachedThreadPool(); public static void main(String[] args) { SwingWorker<Void, Void> worker = new SwingWorker<>() { @Override protected Void doInBackground() throws Exception { // Perform some task that may throw an exception ... // Re-throw any caught exceptions using ExecutionException throw new ExecutionException(new Exception("Error occurred in doInBackground()"), null); } @Override protected void done() { try { get(); // Will throw the re-thrown ExecutionException } catch (ExecutionException e) { // Handle the exception here e.printStackTrace(); } catch (InterruptedException e) { // Handle the interruption here e.printStackTrace(); } } }; executor.execute(worker); } }
登录后复制
按照以下步骤,您可以捕获并处理由 SwingWorker 任务执行的异常执行器,确保未捕获的异常不会被默默地忽视。
以上是如何处理Executor执行SwingWorker任务的异常?的详细内容。更多信息请关注PHP中文网其他相关文章!
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章
R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 个月前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
1 个月前
By 尊渡假赌尊渡假赌尊渡假赌
刺客信条阴影:贝壳谜语解决方案
3 周前
By DDD
Windows 11 KB5054979中的新功能以及如何解决更新问题
2 周前
By DDD
威尔R.E.P.O.有交叉游戏吗?
1 个月前
By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)
