在java当中,异常一共分为两种。一种是运行时异常,一种是非运行是异常。
非运行时异常:这些异常必须在方法上通过throws子句抛出。或者在方法体内进行try{…}catch{…}来捕获异常。
运行时异常: 这些方法不需要在throws子句抛出,也不需要在方法体内进行try{}catch{}操作。
在ForkJoin框架中声明的compute()方法不允许在运行是抛出异常,因为这个方法的实现没有包含任何throws申明。因此,必须包含必须的代码来处理相关的异常。
下面通过一个示例来说明这种情况。
首先创建一个ForkJoin框架执行的任务类。
Task.java
public class Task extends RecursiveTask<Integer>{ private static final long serialVersionUID = 1L; private int array[]; private int start,end; public Task(int array[],int start,int end){ this.array = array; this.start = start; this.end = end; } protected Integer compute() { System.out.printf("Task:Start from %d to %d\n",start,end); if(end-start<10){ if((start<3)&&(3<end)){ throw new RuntimeException("This task throws an"+"Exception:Task from "+start+"to "+end); } else{ try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } else{ int mid = (end+start)/2; Task task1 = new Task(array,start,mid); Task task2 = new Task(array,start,mid); invokeAll(task1,task2); } System.out.printf("Task:End form %d to %d \n",start,end); return 0; } }
然后是执行的主类:
public class Main { public static void main(String[] args) { int array[] = new int[100]; Task task = new Task(array,1,100); ForkJoinPool pool = new ForkJoinPool(); pool.execute(task); pool.shutdown(); try { pool.awaitTermination(1,TimeUnit.DAYS); } catch (InterruptedException e) { e.printStackTrace(); } if(task.isCompletedAbnormally()){ System.out.print("Main:An exception has occured\n"); System.out.printf("Main:%s\n",task.getException()); } } }
运行结果为:
Task:Start from 1 to 7 Task:Start from 1 to 7 Task:Start from 1 to 13 Task:Start from 1 to 7 Task:Start from 1 to 7 Main:An exception has occured Main:java.lang.RuntimeException: java.lang.RuntimeException: This task throws anException:Task from 1to 7