question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Help newbies to handle exceptions in coroutines

See original GitHub issue

I can’t figure how to catch the exceptions thrown from a launch block. I don’t understand how to use the CoroutineExceptionHandler. I think that the Try pattern is quite heavy (https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/src/test/kotlin/kotlinx/coroutines/experimental/Try.kt). The CompletableFuture wrapper works as expected (simply), but it requires the jdk8 lib. Thanks for this masterpiece !

import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.future.await
import kotlinx.coroutines.experimental.future.future
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.runBlocking
import org.junit.Ignore
import org.junit.Test
import java.util.concurrent.atomic.AtomicBoolean

class CoroutinesTest {

    class TestException: Exception("test exception")

    @Test
    @Ignore("not that way...")
    fun testExceptionOnLaunch_tryCatch() {
        runBlocking {
            val caught = AtomicBoolean(false)
            val job = launch(context) {
                delay(10)
                throw TestException()
            }
            try {
                job.join()
            } catch (e: TestException) {
                caught.set(true)
            } finally {
                assert(caught.get())
            }
        }
    }

    @Test
    @Ignore("not that way...")
    fun testExceptionOnLaunch_getCompletionException() {
        runBlocking {
            val job = launch(context) {
                delay(10)
                throw TestException()
            }
            try {
                job.join()
            } finally {
                val exc = job.getCompletionException()
                assert(exc is TestException)
            }
        }
    }

    @Test
    fun testExceptionOnFuture() {
        System.setProperty("kotlinx.coroutines.debug", "off")
        runBlocking {
            val caught = AtomicBoolean(false)
            val job = future(context) {
                delay(10)
                throw TestException()
            }
            try {
                job.await()
            } catch (e: TestException) {
                caught.set(true)
            } finally {
                assert(caught.get())
            }
        }
    }
}

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:7
  • Comments:25 (8 by maintainers)

github_iconTop GitHub Comments

47reactions
Zedonboycommented, Apr 11, 2018

Honestly Kotlin seems to be a crap in the long term, more like wheel reinventing. Didn’t use beautiful features of C#, Java, just created a new way of doing everything things.

So kotlin is trying to say that, i cant handle error like the popular Promise way? example Defered.onError(//pass a lambda here),

The learning curve is fucking high, Docs didnt explain things well. all i gain is

  1. Null Safety(Java is already doing well with that)
  2. Concise (Still difficult to read a Kotlin Code, coming from a static typing world)
  3. No Performance Gain
  4. No Domain Specific Feature(like Scala in Distributed Computing)

I really want to help in the Docs, fuck coroutines. (Not really happy with this kotlin, I feeling threatened my Java was getting obsolete and wasted my time learning kotlin)

I still Love The Challenge Kotlin is giving me though, good work guys 😃

24reactions
elizarovcommented, May 30, 2017

You can switch to async instead of launch and use await instead of join. This way exceptions will percolated to the functions that await. I’ll keep this issue open, because there is definitely a need for a more detailed explanation in docs.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Exceptions in coroutines. Cancellation and Exceptions in…
Coroutines use the regular Kotlin syntax for handling exceptions: try/catch or built-in helper functions like runCatching (which uses try/catch internally). We ...
Read more >
Why exception handling with Kotlin Coroutines is so hard and ...
If a Coroutine doesn't handle exceptions by itself with a try-catch clause, the exception isn't re-thrown and can't, therefore, be handled by an ......
Read more >
Exception handling in Kotlin Coroutines - Kt. Academy
Just as a program breaks when an uncaught exception slips by, a coroutine breaks in the case of an uncaught exception. This behavior...
Read more >
Coroutine exceptions handling | Kotlin
We already know that a cancelled coroutine throws CancellationException in suspension points and that it is ignored by the coroutines' machinery ...
Read more >
Exception Handling in Kotlin Coroutines - MindOrks
In this blog, we are going to talk about how we can handle exceptions while using Kotlin Coroutines. We will discuss various ways...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found