Error Handling in Futures
Implement strategies for handling exceptions and failures gracefully within asynchronous `Future` computations.
Error Handling in Futures is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 3 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Handling Future Failures
Asynchronous operations can fail! Just like synchronous code can throw exceptions, a Future can complete with an error instead of a successful value.
Understanding how to gracefully handle these failures is crucial for building robust concurrent applications. Without proper error handling, your program might crash or behave unexpectedly.
Future's Result: Try
When a Future completes, its result is wrapped in a scala.util.Try. This Try can be either a Success(value) or a Failure(exception).
- Success: Contains the computed value.
- Failure: Contains the exception that occurred.
The onComplete callback receives this Try object, allowing you to handle both outcomes.
Using onComplete for Errors
The onComplete method is a universal listener for a Future's completion. It takes a function that accepts a Try[T].
You can pattern match on the Try to distinguish between success and failure.
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Success, Failure}
object Main {
def main(args: Array[String]): Unit = {
val failingFuture = Future {
if (true) throw new RuntimeException("Oops!")
10
}
failingFuture.onComplete {
case Success(value) => println(s"Success: $value")
case Failure(exception) => println(s"Failure: ${exception.getMessage}")
}
Thread.sleep(100) // Keep JVM alive for Future to complete
}
}The recover Method
recover allows you to handle an exception and provide a fallback value if the Future fails. It transforms a Future[T] into another Future[T].
If the original Future fails, the provided partial function is applied to the exception. If it matches, a new successful Future with the fallback value is returned.
recover Example
Here, if the division by zero occurs, recover catches the ArithmeticException and returns a Future with the value 0.
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
object Main {
def main(args: Array[String]): Unit = {
val resultFuture = Future { 10 / 0 } // This will fail
val recoveredFuture = resultFuture.recover {
case e: ArithmeticException =>
println("Caught ArithmeticException, recovering...")
0 // Fallback value
}
recoveredFuture.foreach(value => println(s"Result: $value"))
Thread.sleep(100) // Keep JVM alive
}
}The recoverWith Method
recoverWith is similar to recover, but instead of returning a fallback value, it returns a fallback Future.
This is useful when your recovery action itself involves another asynchronous operation, or if you want to retry the original operation.
recoverWith Example
If the initial future fails, recoverWith provides a new future that attempts a different operation or a default async value.
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
object Main {
def main(args: Array[String]): Unit = {
val primaryOperation = Future {
if (true) throw new Exception("Primary failed!")
100
}
val fallbackOperation = Future {
println("Running fallback operation...")
50
}
val finalFuture = primaryOperation.recoverWith {
case e: Exception =>
println(s"Primary failed: ${e.getMessage}. Using fallback.")
fallbackOperation
}
finalFuture.foreach(value => println(s"Final result: $value"))
Thread.sleep(200) // Keep JVM alive
}
}The fallbackTo Method
fallbackTo allows you to chain two Futures. If the first Future fails, its result is ignored, and the result of the second Future is used instead.
Unlike recoverWith, fallbackTo doesn't inspect the exception. It simply says: "If this one fails, try that one."
fallbackTo Example
Here, if failingFuture fails, fallbackTo will use the result of backupFuture.
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
object Main {
def main(args: Array[String]): Unit = {
val failingFuture = Future {
if (true) throw new RuntimeException("Network error!")
"Data from primary"
}
val backupFuture = Future {
println("Using backup source...")
"Data from cache"
}
val finalResult = failingFuture.fallbackTo(backupFuture)
finalResult.foreach(value => println(s"Retrieved: $value"))
Thread.sleep(100) // Keep JVM alive
}
}Error Handling Quiz
Which method would you use if you want to provide an alternative asynchronous operation when a Future fails?
Recap: Future Error Handling
We've explored key strategies for handling errors in Scala Futures:
onComplete: Reacts to both success and failure with aTry.recover: Provides a fallback value if an exception occurs.recoverWith: Provides a fallbackFutureif an exception occurs.fallbackTo: Uses a backupFutureif the primary one fails, without inspecting the error.
These methods are essential for building resilient asynchronous systems!
Frequently asked questions
Is the “Error Handling in Futures” lesson free?
Yes — the full text of “Error Handling in Futures” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.
What will I learn in “Error Handling in Futures”?
Implement strategies for handling exceptions and failures gracefully within asynchronous `Future` computations. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Scala for Backend Engineering & Functional Programming?
No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “Error Handling in Futures” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?
Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Introduction to Futures and Promises
- Composing Asynchronous Operations
- Error Handling in Futures