実行する作業の大きなブロックを定義するクラスがあり、いくつかのチェックされた例外を生成できるとします。
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.