Die*_*rDP 7 java swingworker executionexception
假设我有一个类定义了要完成的大块工作,可以产生几个已检查的异常.
class WorkerClass{
public Output work(Input input) throws InvalidInputException, MiscalculationException {
...
}
}
Run Code Online (Sandbox Code Playgroud)
现在假设我有一个可以调用这个类的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);
}
};
Run Code Online (Sandbox Code Playgroud)
如何处理从SwingWorker抛出的可能异常?我想区分我的worker类的异常(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.
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10066 次 |
最近记录: |