简体   繁体   中英

scala, exception handling, promises

I am beginner in Scala and I have a problem with exception handling

Code

val f = future { throw new Exception }
val p = promise[Int]
p completeWith f
p.future onFailure  {
  case t => println("An error has occured: " + t)
}
p.future onSuccess {
  case x => println(x)
}
Await.result(f, 10 seconds)

and as a result I got string An error has occured: java.lang.Exception , but it is followed by an Exception and program terminates.

What is wrong with this program ?

Await.result is a very blunt instrument. If the future fails, it will just throw the exception. You could skip all the lines between the first and last and you'd get the same result.

Additionally, onFailure doesn't provide error handling , properly understood—it's just a way to make something happen if the future fails. To actually handle errors, use recover or recoverWith (note that I'm using Future instead of future , which is now deprecated):

val f = Future { throw new Exception }

val r = f.recover {
  case t => println("An error has occured: " + t); 13 // some default value
}

Now you can block and wait for r with Await.result(r, 10.seconds) .

Await will rise the exception again for you in the main thread.

if you make

try {
  Await.result(f, 10 seconds)
}
catch {
  case a => prinln("here")
}

your code will execute the println("here") line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM