簡體   English   中英

結合期貨和例外

[英]Combining futures and exceptions

我試圖了解期貨如何與例外結合。 函數FutureA返回一個Future或引發異常。 當我嘗試捕獲異常時,什么也沒有發生。 這是為什么?

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)
}

這是如何捕獲返回期貨的函數可能引發的異常:

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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM