2016-04-17 1 views
1

例外をキャッチする一般的なアドバイスは、もっとも広いクラスの例外(java.lang.Exception)をキャッチするのではなく、具体的にする方がよいということです。ExecutorServiceとCallableを使用して特定の例外をキャッチできませんか?

しかし、Callableからの唯一の例外はExecutionExceptionだと思われます。

package com.company; 

import java.util.ArrayList; 
import java.util.List; 
import java.util.concurrent.*; 

public class ThreadTest { 

    private final static ArrayList<Callable<Boolean>> mCallables = new ArrayList<>(); 
    private final static ExecutorService mExecutor = Executors.newFixedThreadPool(4); 

    public static void main(String[] args) throws Exception{ 
     testMethod(); 
    } 

    static void testMethod() throws Exception { 

     mCallables.clear(); 

     for(int i=0; i<4; i++){ 
      mCallables.add(new Callable<Boolean>() { 

       @Override 
       public Boolean call() throws Exception { 
        //if (Thread.currentThread().isInterrupted()) { 
        // throw new InterruptedException("Interruption"); 
        //} 
        System.out.println("New call"); 

        double d = Double.parseDouble("a"); 

        return true; 
       } //end call method 

      }); //end callable anonymous class 
     } 
     try { 
      List<Future<Boolean>> f= mExecutor.invokeAll(mCallables); 
      f.get(1).get(); 
      f.get(2).get(); 
      f.get(3).get(); 
      f.get(0).get(); 

     } catch (NumberFormatException e) { 
      e.printStackTrace(); 
      System.out.println("Number Format exception"); 
     } catch (ExecutionException e) { 
      String s = e.toString(); 
      System.out.println(s); 
      System.out.println("Execution exception"); 
     } catch (Exception e) { 
      System.out.println("Some other exception"); 
     } 

     mExecutor.shutdown(); 
    } 
} 

上記のコードでは、NumberFormatExceptionをキャッチしたいと思いますが、ExecutionException以外は何もキャッチしていないようです。

呼び出しメソッドから複数の異なる例外がスローされた場合、どのようにして別々の例外を個別にキャッチするのでしょうか?

答えて

4

いつもExecutionExceptionが表示されます。ルート例外が原因として設定されます。 インスタンスのgetCause()を呼び出して、Callableにスローされた実際の例外を取得します。

関連する問題