处理ExecutionException的原因

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)

Mik*_*rov 5

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)

  • 在某些情况下,许多人想代替`throw e`来抛出`new new RuntimeException(ee)`。 (2认同)