I'm confused by how to properly use CoroutineExcep...
# coroutines
d
I'm confused by how to properly use CoroutineExceptionHandler. I tried:
Copy code
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.system.exitProcess

fun main() = runBlocking {
	val handler = CoroutineExceptionHandler { _, t ->
		println("handling exception: $t")
		exitProcess(1)
	}
	coroutineScope {
		launch(handler) {
			println("running")
			throw Exception("OMG")
		}
	}
	Unit
}
I would expect this to print "handling exception" and exit the process. Instead it shows that an exception was unhandled in
main
(I'll paste in the thread)
Copy code
running
Exception in thread "main" java.lang.Exception: OMG
	at mdg.engine.selfmonitoring.TmpKt$main$1$1$1.invokeSuspend(tmp.kt:17)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
	at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241)
	at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.common.kt:270)
	at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:79)
	at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:54)
	at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
	at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:36)
	at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)
	at mdg.engine.selfmonitoring.TmpKt.main(tmp.kt:9)
	at mdg.engine.selfmonitoring.TmpKt.main(tmp.kt)
Oh hmm. Maybe this is related to:
This also a reason why, in these examples, CoroutineExceptionHandler is always installed to a coroutine that is created in GlobalScope. It does not make sense to install an exception handler to a coroutine that is launched in the scope of the main runBlocking, since the main coroutine is going to be always cancelled when its child completes with exception despite the installed handler.
at https://kotlinlang.org/docs/reference/coroutines/exception-handling.html
g
Exception handler doesn’t make sense for such use case in general, particularry it doesn’t work here because you use coroutineScope isntead of supervisorScope
d
indeed, try/catch was fine