结合期货和例外

时间:2017-12-01 19:03:46

标签: scala

我试图了解期货如何与例外相结合。函数FutureA要么返回一个未来,要么抛出一个异常。当我试图捕捉异常时,没有任何反应。那是为什么?

package test

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global


object TestFutures extends App {

  def futureA(x: Int) = Future { 
    if (x==1)
      1
    else
        throw new Exception("there's an error")
  }

   try {
       futureA(2)
   }
   catch {
     case ex:Exception => println("an exception was thrown")     

   }

   println("end")
   Thread.sleep(15000)
}

1 个答案:

答案 0 :(得分:1)

这是捕获返回期货的函数可以抛出的异常的方法:

package test

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global


object TestFutures extends App {

  def futureA(x: Int) = Future { 
    if (x==1)
      1
    else
        throw new Exception("there's an error")
  }

    futureA(2).map { result =>
         println("OK")
    }
    .recover{ 
        case ex:Exception => println("an exception was thrown")     
     }

   println("end")
   Thread.sleep(15000)
}