Kotlin unhandled coroutine exception does not crash

Issue

I expected the following program to crash but it doesn’t. It just prints that an exception occurred in a thread and exits normally. Why?

import kotlinx.coroutines.*

fun main() {
    val scope  CoroutineScope(Dispatchers.Default)

    scope.launch {
        delay(100)
        throw RuntimeException("1")
    }

    println("sleep")
    Thread.sleep(1000)
    println("exit without crash")
}

playground

Solution

Since you’re creating your own CoroutineScope, you have your own top-level coroutine which is not bound to the main thread. Creating a CoroutineScope manually also implies manual cleanup (otherwise you have the same pitfalls as GlobalScope and may leak coroutines or lose errors).

The main program only crashes if the main thread crashes, and the main thread doesn’t crash here. If you want to have a relationship between this main thread and the launched coroutines (and propagate exceptions), you should use structured concurrency from the beginning.

For instance, using runBlocking at the top of your main() function creates a CoroutineScope (available as this) which serves as parent for all launched coroutines. It also blocks the main thread while waiting for all the child coroutines, and propagates exceptions. You don’t need your own scope then:

fun main() {
    runBlocking(Dispatchers.Default) { // using Dispatchers.Default to be equivalent with your code

        launch { // using "this" CoroutineScope from runBlocking
            delay(100)
            throw RuntimeException("1")
        }

        println("sleep")
        delay(1000) // using delay instead of Thread.sleep because we're in a coroutine now
        println("exit without crash")
    }
}

This way you get:

sleep
Exception in thread "main" java.lang.RuntimeException: 1
 at FileKt$main$1$1.invokeSuspend (File.kt:16) 
 at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith (ContinuationImpl.kt:33) 
 at kotlinx.coroutines.DispatchedTask.run (DispatchedTask.kt:106) 

Answered By – Joffrey

Leave a Comment