在java当中,异常一共分为两种。一种是运行时异常,一种是非运行是异常。
非运行时异常:这些异常必须在方法上通过throws子句抛出。或者在方法体内进行try{…}catch{…}来捕获异常。 运行时异常: 这些方法不需要在throws子句抛出,也不需要在方法体内进行try{}catch{}操作。在ForkJoin框架中声明的compute()方法不允许在运行是抛出异常,因为这个方法的实现没有包含任何throws申明。因此,必须包含必须的代码来处理相关的异常。
下面通过一个示例来说明这种情况。 首先创建一个ForkJoin框架执行的任务类。Task.java
public class Task extends RecursiveTask{ 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
然后是执行的主类:
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 7Task:Start from 1 to 7Task:Start from 1 to 13Task:Start from 1 to 7Task:Start from 1 to 7Main:An exception has occuredMain:java.lang.RuntimeException: java.lang.RuntimeException: This task throws anException:Task from 1to 7