gpt4 book ai didi

java - Swing Worker 中的优雅异常处理

转载 作者:IT老高 更新时间:2023-10-28 20:30:38 24 4
gpt4 key购买 nike

我通过 Swing Worker 类在应用程序中使用线程。它工作正常,但我对在 try-catch block 中显示错误消息对话框有一种不好的感觉。它可能会阻止应用程序吗?这就是现在的样子:

SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

// Executed in background thread
public Void doInBackground() {
try {
DoFancyStuff();
} catch (Exception e) {

e.printStackTrace();

String msg = String.format("Unexpected problem: %s", e
.toString());

//TODO: executed in background thread and should be executed in EDT?
JOptionPane.showMessageDialog(Utils.getActiveFrame(),
msg, "Error", JOptionPane.ERROR_MESSAGE,
errorIcon);

}//END: try-catch

return null;
}

// Executed in event dispatch thread
public void done() {
System.out.println("Done");
}
};

是否可以使用 Swing Worker 框架以安全的方式完成?重写 publish() 方法是一个很好的方法吗?

编辑:

是这样的吗:

} catch (final Exception e) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

e.printStackTrace();

String msg = String.format(
"Unexpected problem: %s", e.toString());

JOptionPane.showMessageDialog(Utils
.getActiveFrame(), msg, "Error",
JOptionPane.ERROR_MESSAGE, errorIcon);

}
});

}

在 done 方法中调用 get 会导致两个 try-catch block ,因为计算部分会抛出异常,所以我认为这最终会更干净。

最佳答案

正确的做法如下:

SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
// Executed in background thread
protected Void doInBackground() throws Exception {
DoFancyStuff();
return null;
}

// Executed in EDT
protected void done() {
try {
System.out.println("Done");
get();
} catch (ExecutionException e) {
e.getCause().printStackTrace();
String msg = String.format("Unexpected problem: %s",
e.getCause().toString());
JOptionPane.showMessageDialog(Utils.getActiveFrame(),
msg, "Error", JOptionPane.ERROR_MESSAGE, errorIcon);
} catch (InterruptedException e) {
// Process e here
}
}
}

您不应该尝试在后台线程中捕获异常,而是让它们传递给 SwingWorker 本身,然后您可以通过调用 get 在 done() 方法中获取它们() 通常返回 doInBackground() 的结果(在您的情况下为 Void)。如果在后台线程中抛出异常,则 get() 将抛出异常,并包裹在 ExecutionException 中。

还请注意,覆盖的 SwingWorker 方法是 protected 的,您不需要将它们设为 public

关于java - Swing Worker 中的优雅异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6523623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com