您可以扩展 SwingWorker 以在创建堆栈时记录堆栈(或在执行时,但您需要创建另一个执行方法,因为它是最终的)。创建原因是相对昂贵的,所以你可能只想在调试时这样做(检查日志级别或类似的)
import java.util.concurrent.ExecutionException;
import javax.swing.SwingWorker;
public abstract class TracedSwingWorker<T, V> extends SwingWorker<T, V> {
private final Exception cause;
public TracedSwingWorker() {
super();
this.cause = new Exception("TracedSwingWorker created at:");
}
@Override
protected final T doInBackground() throws Exception {
try {
return doWorkInBackground();
}
catch(Exception e) {
if(this.cause != null) {
Throwable cause = e;
while(cause.getCause() != null) {
cause = cause.getCause();
}
cause.initCause(this.cause);
}
throw e;
}
}
protected abstract T doWorkInBackground();
// just for testing
public static void main(String[] args) {
new TracedSwingWorker<Void, Void>() {
@Override
protected Void doWorkInBackground() {
throw new IllegalArgumentException("Exception in TracedSwingWorker!");
}
@Override
protected void done() {
try {
get();
}
catch (InterruptedException e) {
e.printStackTrace();
}
catch (ExecutionException e) {
e.printStackTrace();
}
}
}.execute();
}
}
印刷:
java.util.concurrent.ExecutionException: java.lang.IllegalArgumentException: Exception in SwingWorker!
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
<snip>
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.Exception: SwingWorker created at:
at TracedSwingWorker.<init>(TracedSwingWorker.java:15)
at TracedSwingWorker$2.<init>(TracedSwingWorker.java:60)
at TracedSwingWorker.main(TracedSwingWorker.java:60)