第一个函数testThrowException 不返回Future 在它获得0 作为输入的情况下。因此,程序会一直运行,直到出现异常。
但是,如下面粘贴的源代码所示,Future.map 总是返回另一个未来:
def map[S](f: T => S)(implicit executor: ExecutionContext): Future[S] = { // transform(f, identity)
val p = Promise[S]()
onComplete { v => p complete (v map f) }
p.future
}
仅仅定义一个 Future 不会打印出它的结果,也不会打印出抛出的异常。为此,您需要定义 onSuccess、onFailure 或 onComplete。但是,如果 Future 的主体中存在 print 语句,那么它将执行:
def addOne(number: Int): Int = {
if (number == 0) {
// you can also print the exception instead of just throwing it.
throw new Exception("number is 0")
} else {
println("success")
1 + number
}
}
Future { addOne(1) } // scala.concurrent.Future[Int] = Future(Success(2))
// the above also prints "success"
Future { addOne(0) } // scala.concurrent.Future[Int] = Future(Failure(java.lang.Exception: number is 0))
// the above does not print anything unless the exception is printed before thrown in `addOne`
您也可以使用onComplete,处理成功和/或失败:
// prints "got error" plus the stack trace
- List item
Future {0}.map(addOne).onComplete {
case Success(value) => println(s"got $value")
case Failure(t) => println("got error: " + t.getStackTrace.mkString("\n"))
}
请注意,使用的导入是:
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}