ps0604
ps0604

Reputation: 1081

Throw exception from within a future

I need to throw an exception in my program, but the exception happens within a future, so it is thrown in a different thread. How to make this example work?

object TestFutures extends App {

  val f0 = Future { 0 }
  val f1 = Future { 1 }
  val fx = Seq(f0,f1)

  fx.map { 
    seq => seq.map {  i =>
        println("i="+i)
        if (i == 1)
              throw new Exception("This is an exception")

    }
  }


  Thread.sleep(5000)
}

This is the program output, but I need it to throw the exception:

i=0
i=1

Upvotes: 1

Views: 1173

Answers (2)

Ivan
Ivan

Reputation: 462

Result is still a Future

 val stillFutures: Seq[Future[Unit]] = fx.map {
    seq => seq.map {  i =>
      println("i="+i)
      if (i == 1)
        throw new Exception("This is an exception")

    }
  }

You can check each future on Success/Failure

stillFutures.foreach{
_.onComplete{
  case Success(_) => // do nothing
  case Failure(ex) => throw ex
}}

Upvotes: 3

Ramesh Maharjan
Ramesh Maharjan

Reputation: 41987

How to make this example work?

You can use for to make it work as

val f0 = Future { 0 }
val f1 = Future { 1 }
val fx = Seq(f0,f1)

for(seq <- fx){
  for(i <- seq) {
    println("i="+i)
    if (i == 1) {
      throw new Exception("This is an exception")
    }
  }
}
Thread.sleep(5000)

Upvotes: 0

Related Questions