Library contents

Kotlin ExecutionException

A failed JVM future wraps its original error in ExecutionException when its result is requested.

A simple example

ExecutionException

  1. Start with A background task fails during conversion
  2. Do this Collect its result
  3. Result Wrapper holds the conversion failure
Inspecting the cause shows what failed inside the task.

Syntax

Kotlin syntax
job.get()
Run these examples in Kotlin

Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

Find 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.

ResultInvalid price
Lesson.kt
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutionException

fun main() {
    val job = CompletableFuture<Int>()
    try {
        job.completeExceptionally(IllegalArgumentException("Invalid price"))
        println(job.get())
    } catch (problem: ExecutionException) {
        println(problem.cause?.message)
    }
}
Output
Invalid price

Collecting the failed job exposes the original price error as its cause.

Advertisements

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.

GivenCompleted tally
Worked resultJob complete

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.

GivenWorker failed
Worked resultReview job

What to watch for

Handle an interrupted wait separately from a failure inside the job.

Documentation for ExecutionException