Groovy ExecutionException
A failed JVM future wraps its original error in ExecutionException when its result is requested.
A simple example
ExecutionException
- Start with A background task fails during conversion
- Do this Collect its result
- Result Wrapper holds the conversion failure
Syntax
job.get()
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyFind the reason a background import failed
A shop processes a price list in a background job. The job encounters an invalid price, and the reporting screen needs the original reason when it collects the result.
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutionException
def job = new CompletableFuture<Integer>()
try {
job.completeExceptionally(new IllegalArgumentException("Invalid price"))
println(job.get())
} catch (ExecutionException problem) {
println(problem.cause.message)
}
Invalid price
Collecting the failed job exposes the original price error as its cause.
Collect a successful tally
A worker has finished adding attendance totals. Collect the worker result. When the background operation failed, mark the job for review.
Review a failed export
A background exporter has recorded a failure from its reader. Collect the worker result. When the background operation failed, mark the job for review.
What to watch for
Handle an interrupted wait separately from a failure inside the job.