Kevin Meredith
Kevin Meredith

Reputation: 41939

Exception Passing Through scala.concurrent.Future?

Is it possible for an exception to be thrown, escaping the Future context?

Since a Future "evaluates" as soon as it's defined:

is it possible for the definition of a Future to throw an exception, passing through the Future context?

scala> Future { Thread.sleep(3000); println("3 seconds elapsed"); 100 }
res2: scala.concurrent.Future[Int] = 
     scala.concurrent.impl.Promise$DefaultPromise@56113384

scala> 3 seconds elapsed

I could not come up with such an example.

scala> Future { throw new Exception("Foo!") }
res3: scala.concurrent.Future[Nothing] = 
  scala.concurrent.impl.Promise$DefaultPromise@47a86fbb

Upvotes: 0

Views: 285

Answers (3)

Nishan
Nishan

Reputation: 365

Why you want to throw an error from your future?

Future is a monad which will handles latency and exceptions while you are dealing with it.

If you look at Future implementation it looks like as below,

trait Future[T] {    def onComplete(callback: Try[T] => Unit)(implicit exe..) }

So when as soon as your future gets complete and value available your callback method will be invoked and return unit.

If you see callback method you will get idea your result would be success or error and Try[T] woluld manage all the things for you.

Upvotes: 0

LuxuryMode
LuxuryMode

Reputation: 33771

A future in itself does nothing except define the computation. It just so happens to be you're using one of the constructors (or apply methods) that, by default, begins running the computation immediately. The mixing of exception handling and concurrency is one of the issues that, unfortunately, not explicit with scala.concurrent.Future. A better alternative may be to use scalaz.concurrent.Task which combines error handling with explicit concurrency.

Upvotes: 0

Michael Zajac
Michael Zajac

Reputation: 55569

Yes, but maybe not quite the way you're thinking of. According to the source, only errors that are not NonFatal will escape Future.apply.

 try Success(body) catch { case NonFatal(e) => Failure(e) }

i.e. exceptions like: VirtualMachineError, OutOfMemoryError,StackOverflowError, ThreadDeath, LinkageError, InterruptedException, ControlThrowable.. will go uncaught as they represent a fatal JVM error that you will not be able to handle.

Upvotes: 3

Related Questions