From: http://ifeve.com/fork-join-5/
There are two types of exceptions in Java:
- Checked for exceptions (Checked exceptions): These exceptions must be specified in a throws clause of a method or captured internally. For example: IOException or ClassNotFoundException.
- No exception checked (unchecked exceptions): These exceptions do not have to be specified or captured. For example: NumberFormatException.
In the compute () method of the Forkjointask class, you cannot throw any checked exceptions, because in the implementation of this method, it does not contain any throw (exception) declarations. You must include the necessary code to handle the exception. However, you can throw (or it can be thrown by any method or object using an internal method) without checking for an exception. The Forkjointask and Forkjoinpool classes behave differently than you might expect. The program does not end execution, and you will not see any information about the exception in the console. It is just swallowed up as if it were not thrown (abnormal). You can use some of the methods of the Forkjointask class to learn whether a task throws an exception and what kind of exception it has. In this guide, you will learn how to obtain this information.
Task
Package Com.wenbronk.forkjoin.exception;import Java.util.concurrent.recursivetask;import Java.util.concurrent.TimeUnit;/** * Forkjoin throws Exception handling * Created by Wenbronk on 2017/7/27.*/ Public classTask extends Recursivetask<integer> { Private intarray[]; Private intstart, end; PublicTask (int[] Array,intStartintend) { This. Array =Array; This. Start =start; This. end =end; } @OverrideprotectedInteger Compute () {System. out. printf ("Task:start from%d to%d \ n", start, end); if(End-start <Ten) { if((3> Start) && (3<end)) {System. out. println ("Paochu Yichang"+ Start +" to"+end); Throw NewRuntimeException ("Task from"+ Start +" to"+end); } Try{TimeUnit.SECONDS.sleep (1); }Catch(Exception e) {e.printstacktrace (); } }Else { intMid = (start + end)/2; Task Task1=NewTask (Array, start, mid); Task Task2=NewTask (Array, Mid, end); InvokeAll (Task1, Task2); } System. out. printf ("Task:end from%d to%d \ n", start, end); return 0; }}
Main
Package Com.wenbronk.forkjoin.exception;import Java.util.concurrent.forkjoinpool;import Java.util.concurrent.TimeUnit;/** * Created by Wenbronk on 2017/7/27.*/ Public classExceptionmain { Public Static voidMain (string[] args) {int[] Array =New int[ -]; Task Task=NewTask (Array,0, -); Forkjoinpool Forkjoinpool=NewForkjoinpool (); Forkjoinpool.execute (Task); Forkjoinpool.shutdown (); Try{forkjoinpool.awaittermination (1, timeunit.days); } Catch(interruptedexception e) {e.printstacktrace (); } if(task.iscompletedabnormally ()) {System. out. println ("main::: An exception have occured \ n"); System. out. printf ("main::::%s \ n", Task.getexception ()); } System. out. printf ("Main:result:%d", Task.join ()); }}
Java-forkjoin exception return