Library contents

Scala 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

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

Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.

scalac Lesson.scala
scala Lesson

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.scala
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutionException

object Lesson {
    def main(args: Array[String]): Unit = {
        val job = new CompletableFuture[Int]()
        try {
            job.completeExceptionally(new IllegalArgumentException("Invalid price"))
            println(job.get())
        } catch {
            case problem: ExecutionException =>
                println(problem.getCause.getMessage)
        }
    }
}
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