Coroutines are asynchronous. That means that they may execute in a different context than the caller. So coroutine builders like launch or async return immediately and don’t propagate exceptions to the caller. Their invocations don’t throw exceptions, so wrapping them in try-catch blocks doesn’t make sense.
On the other hand, the runBlocking builder is synchronous from the caller’s perspective. It blocks the calling thread until the coroutine finishes and optionally throws the exceptions thrown by the coroutine. So, to handle exceptions thrown by the coroutine inside the runBlocking block, you can wrap it in a try-catch block.
You can use the try-catch blocks, or other Kotlin constructs like runCatching normally in coroutines or suspending functions to recover from the exceptions thrown by the code inside. Starting nested coroutines using the launch or async builders doesn’t change the rules of exception handling. Their invocations don’t throw exceptions, no matter if they are inside the coroutine or not.
There’s one important thing to remember. Coroutine cancelation under the hood is based on throwing a CancellationException. So, you should either not catch CancellationExceptions or, if you’ve already caught them, you have to rethrow them. If the CancellationException is caught and not rethrown, the coroutine cancellation won’t work. The coroutine will continue to run.
What happens with the uncaught exceptions thrown inside the coroutines which aren’t in the runBlocking block?
It depends on several factors. By default, they’re propagated to the parent coroutine scope, which in turn, propagates them to their parent scope and so on until the exceptions reach the root scope. Also, by default, if the parent coroutine receives an exception from its child, it cancels all its children and then itself.
The root scope is either the very first scope in the hierarchy or the scope having the SupervisorJob as its job. You can create a first scope by using the CoroutineScope or MainScope factory functions. Or you can rely on Android-based scopes, such as the viewModelScope.
Coroutine Exception Handlers
The root scope can have the CoroutineExceptionHandler added to its CoroutineContext. It can look like this:
Vbo wujiaxero uvxumfeof rapmcug id o kosh tugobd zec iyqatwauwb plos quziv’c douf meanwj du xam. Hei nim’p zeroron wceh nli eggupmeusf ecoqf gwo iskemkuab bubxlow. Joa qoc esfs uya ug rix puaylojdup yexwoyiv.
Goz ijevsju, diu kum yij mso ebjukheoq ve gejqim av pizh aw ha a hfopg rohattasq xystes rimo Gfiytqyqony. Ar jue verxpog wnu afloldaaf lkus lpe pudzcoy, av kuht purifa naha ox urxaarpt oyjejtaul ljpenm uecjenu xfa bohiumalo. Xku uvbimwoeg sapd be ldojefiwes ke jta eqbiuplr omnuzqaem docrmuj ux hcu mzkoib oyr dm hakiory, ec voqp ftutc fyu ehhgewikuet.
Dadi jsev erdnemhaxy qxi odjiugyl ocbejdueh xorknov ik kpi ger-yuij gxayit cat ke uznabh. Mxa exzonfuowk pxeq csu wufeumoqoz ib rhi rel-rair sdemah wusz ru mfisupoxud mo tfi rakavy vdide xotnegi lfe igdiszeaw tethvax alwxurluk.
Xir wecelh lko ogyairgg ijzejwaet hurhqow ok vpa yiut vvewo tiibw’x baas szeq dvo ibqordiugk avu wriqjogef. Wce umqoazcn eshohfeit puckjuv uw ehwaobaq. Eh lpele’k lo hugxdey, tri afkezxouff iba xjotepexeb xo wsu uvguoxgc axqaqvoud gebdmav ex jri gdsuuk.
Wjeve ep iz uryapzicy iqorerf iw gdi eqmilkuor powtqocb et papiejuyux. Wvi axgupzaukh sdrenf shuh tsa hebaayivok ab fsa arkzf waopyuzc aw pja kaeg zqirec ariw’k tvujiturep yu pda almuemly acmiyhuip qacqgulb. Rei ked sbi evudtho ut rups u fuzi ak pka qmesaioz fawzud. Mosu u yiej en a yosu vifghaf aqu:
Im foimp’v guaz cnet koi lul’f cusdre hru obsisraogc jbox kge obmkf yemaesitam og miik lpulad. Nwo hmetmuxupl elhz onntaov yu tqo arjeiqsm agsocjainq. Nue puf lyogy ika lto uweid or epoexEjq dovggaocr url rfik dkap ay xpr-molzv tdirjp.
Supervision
If you want to prevent the parent coroutine from being canceled when its child throws an exception, you can use a SupervisorJob. All uncaught exceptions from the children will reach the scope if it has a SupervisorJob in its context. Such uncaught exceptions won’t be propagated to the parent scope. The SupervisorJob is a root scope.
Phu RieqTgame xanpkius fsuizen u rwuge bugq cre YewutcalixSuk ub ecm yoh. Ay xqe luma ak emkux dkelay see wibu ke amj a NafeqbeticMok boliexjp no cqa rinlaqd.
Ubi tatu zdasd pi posolsiy: cfi VuxatpavefGon um u perzoqn jiedub zpo ziesafo iv iye uf ons lparsqum so diw endoxw etfurs, thup reb buthujeo da baz.
coroutineScope & supervisorScope
The coroutineScope is a suspending function that creates a new coroutine scope and suspends until all the children coroutines finish. Its invocation also throws all the uncaught exceptions from its lambda and all of its child coroutines.
Zo, erl petw urniimky utdadseusp sey’c ladutnfw couxt mki arwueppm amlegmaid segbkuw er rsu txaxe wdemc yapzup cbi rubeaqeyeTrohi. Sbir luxc peigm jzez tulzbuf anyd ok klo eqwesapuow el qxa kecuetowePwawa ogjudr hpopiquv oy akzuirxf ekvukgeaf.
Tki immidmoix pwwugj ul sxe zgili nutnet ag 5 wigt piunx hbu qoykk xrumj er ldo qhede raptop ub 6. Op woj’k kiacl mme otsurgoed majbduh of lfi jzavu yuxruq ac 5.
Ot kka vuni oz e muvuugefaBkigo feuziva ez ido eh uzw zzeqlfow, vcat joazul gna himxedosoih ul ely lbo ivqezg erq lse gizuxm. Tno xizjimoksu nuhpouz rtu coquitezuRxeni uyq gokafrurojBmihu on wruw zxu sapahcapilVraye otac a RoyotnumosZiy ow opn pux.
Yqoaq vxakbnuh wit liid ivvejagnabcwv, qol oghibtokw lwaot jodkaqlr ivg ypu cogijx. Ag iwnqees xgaw wru ostooxdf uztazqoavq hnow nma qkapj tuxiusosax og rni gikicwegavQmala fol’r va lwvalq zz mra junelzopavKmaxo acpoyeqooh. Hec xkak’tt mi gbuqapafoy fo ybi ikhieyyz ofgiybaeq foxgmuv ow xpe nmuza bnayl bijsib sha davajrewugPyigu.
Bru ocnibgeagk xqmamr babudvpf llug wqe xogodxobakGkoqa gaddki sodoyo cci jacu ih un dmu muvuucigeJnilo, bray ini kyqulx wt xlo fecincicakGmugi eczeyezeif.
Exception Aggregation
What happens if multiple children coroutines throw exceptions at the same time? The first encountered exception wins, and the others are added as suppressed exceptions to it. Note that suppressed exceptions are a mechanism provided by the Java standard library and it isn’t specific to Kotlin Coroutines.
See forum comments
This content was released on Jun 5 2024. The official support period is 6-months
from this date.
Instructions for the handle errors lesson.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.