Don't you have to await the future? I would guess,...
# coroutines
u
Don't you have to await the future? I would guess, something like this will throw:
Copy code
fun main(args: Array<String>) {
    val f = future {
        throw RuntimeException("Hello!")
    }
    f.await()
}
i
No, I don’t think you need to await the future -
future {}
will start the coroutine. But I can see why the exception would be swallowed, I’m just not sure what the solution is to avoid exceptions being silently swallowed this
a
isn’t it the same as throwing an exception in a newly created thread?
u
nope. I think, the exception is caught on the background thread, saved, and then thrown on await.
when you await the future, you can see it being thrown on the main thread.
Copy code
Exception in thread "main" java.lang.RuntimeException: Hello!
	at GlobalKt$main$1$f$1.doResume(global.kt:31)
	at kotlin.coroutines.experimental.jvm.internal.CoroutineImpl.resume(CoroutineImpl.kt:54)
	at kotlinx.coroutines.experimental.DispatchedContinuation$resume$1.run(CoroutineDispatcher.kt:152)
	at java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1423)
	at java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
	at java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:902)
	at java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1689)
	at java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1644)
	at java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)
i
I’m wondering if I should be using
runBlocking
instead of
future
- since the code just needs to get executed, I don’t care about the result…?
u
then you could use launch. but an exception in a coroutine is treated like a result. So launch as well as future will not throw the exception on the main thread
I am not yet sure, what you are trying to do. If you were using future just to have an environment in which you can await other futures, runBlocking might be OK. runBlocking as it's name sugests, will block your current thread though.