gpt4 book ai didi

java - 处理 ExecutionException 的原因

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:25:43 26 4
gpt4 key购买 nike

假设我有一个类定义了一大块要完成的工作,它可以产生几个检查异常。

class WorkerClass{
public Output work(Input input) throws InvalidInputException, MiscalculationException {
...
}
}

现在假设我有某种可以调用此类的 GUI。我使用 SwingWorker 来委派任务。

Final Input input = getInput();
SwingWorker<Output, Void> worker = new SwingWorker<Output, Void>() {
@Override
protected Output doInBackground() throws Exception {
return new WorkerClass().work(input);
}
};

如何处理 SwingWorker 可能抛出的异常?我想区分我的工作类的异常(InvalidInputException 和 MiscalculationException),但是 ExecutionException 包装器使事情变得复杂。我只想处理这些异常 - 不应捕获 OutOfMemoryError。

try{
worker.execute();
worker.get();
} catch(InterruptedException e){
//Not relevant
} catch(ExecutionException e){
try{
throw e.getCause(); //is a Throwable!
} catch(InvalidInputException e){
//error handling 1
} catch(MiscalculationException e){
//error handling 2
}
}
//Problem: Since a Throwable is thrown, the compiler demands a corresponding catch clause.

最佳答案

catch (ExecutionException e) {
Throwable ee = e.getCause ();

if (ee instanceof InvalidInputException)
{
//error handling 1
} else if (ee instanceof MiscalculationException e)
{
//error handling 2
}
else throw e; // Not ee here
}

关于java - 处理 ExecutionException 的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14729834/

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