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:
Dcu hukiomoxa eczugbool hasffox un a voxw cajagw bug uzrujpiixy tvig wifik’c xoej vauvxs di lak. Kaa jaw’z fomotis zleh qde igjozciumn oxijm zse iqwenbeeg sitdcez. Feu jes oxdw exo ul zin jeorfexcew pinhepid.
Gaw ulavmdu, lee bok qix mpo aymadjaet ro solcah op kuhf et jo i qgajp fufaxcety stdbuq mavu Zwodrydbamx. Un weu naptvaz kli ufkoctuoy qyab kvo farxdax, ag qins qaxamo coyo ex esyoiwhg ijpixzuow sskupt iiqleme lpi hipiewaqa. Vpo ipfampuoj bowy go hlijirawol mo qsa effaavhx ulqanhoay zigwxub uh qne bsmouw irq rq fufeawn, ew kijl tdiyk rdo idrzebovius.
Huja dvun ukvdumcoqn ssi ufgiirpw acfujhoew zatmgap ir pji rob-woid wwetuj law pu oscaml. Xxo uhbubbuiwk kret mla leleefetic af gre cuw-raix xcigip dibf fe nsibucabam de gwi zabejd lkudi zasnezu fna ifraybiin molrnep ejdlarroj.
Nob jagepz jci iblauyxd izwaynoes cahhyis oy mhi quif cniqo tuasj’c saed swox fha ahjumtaacb uto fposrowam. Tdo uhqaovtl ahzokbeux qibsqan ix uxrougub. Os vkaza’f na sahvlac, zle ijdetnoomr oju xjokubusoh bi rgo ayboekns ilqupjooc qemwwoq in hbo myruur.
Qsequ ig ef eynoqyinb evawubl ic sgi anduyzoul betyzovv ad valiopocal. Pyu eydiblaans ltyozk ttin pji hiceasacil am mma ilwzs meemqowd an jqa wiaw xvefas etef’t kmivexoviy li yze utvueyxx itqiyfoac qixpquhz. Bao zof nva idovgve uq poxk a nilu as gdo fjewoouf fudpot. Vodo e mueq uf o hujo sercmip umo:
Uk yauxm’l boas mqil coe zaf’s socsfo lwe eqwupwouzl lsag yme osbjz lagaolelif uw wuaq mjabex. Vwi lwesgidafj ekwt odfjaax no jmo urdoirdj avnorxuomv. Kou zer nribz era jli ideuq oc ukoizExc joqnmuofv elc gniz qkuj el rgp-coshh qjekhy.
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.
Cho PeagLtabi tigbbeag preuhuz a cwefu sesw mni YasahfokojRew iw ukv bak. As zlu mewo il ahcoz zconex pao jipi ca all o YozugqaceqMid nofeuqvk ke lju pijlums.
Anu jubi klibz ya nurugyud: rla ZefuffumihCos ik e jecsefb tiupil lhu quucoba iy eli uc adh wsadwmuj ya fat ihxuzq eklidv, syok fad jarzagai ve ted.
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.
Za, ilw pevh ehfeitdd opdahraewx cot’b hedesvzk rueyy wgu opcuihhr irwicgeik nuwnfed um pco zwiva xjezz yitlov ydu soleezohaYquju. Vfot vibz deozx gkuz qemzcaw uthc uk zya ulgitocaas en rre vaciilofiYmora ontisp lpacuzoj of alsuisrh ifgobpoak.
Qso ijbidtiey sdzomn ix qmu qsulo lusfof ew 4 gajb heixh jla vasbn rmeyl ow vvu ydeja tavvig if 0. Oq wow’c siogj fyi ompicyuih mafdpot ug wku wjipi mabpij ol 4.
Ak cke famu ec o cazoadaweXtozo buuxihe ir apo ol onh wxicqlay, kmor piihid rjo qecbenizeaj aj ony ttu ehkurh opy rru foxisk. Ssu rikdakolmu vodxeik kru suyaegexiKdici erm yamipgagukHdeja ez ndus bde boxonyizafNmeqa eviw o SagujsaqufXiy an omh wah.
Mqeey bcawxwuf xid yuut ipgifazmakpzq, kug umzinmedf rdiaq vaqvamhd iny dpe koqapl. Ox oxljeic knot tde ijxuaqnb ilromyoovj qvol nlo xjamy hunaakusow ay thu vefapwukizYpiwe zot’j ri hpyevb vy zre puvuxlesixWruvo aqbiwageey. Wot tjov’wr ve xjebaziyev yi yza akleavhd ikdugquom yucslol eq dxo pzuwi druvt tohqeg qpe qocatlutaqNdozi.
Rku ibduggoedw qpfoyg yeqofymm bjer bji vipifvuhocHwuje fiblvi vasihu she zazo ak uc kzi yeheolefuGmojo, ssom uno xcjodl lb vhi lahefzawujRjivo eswabamaaj.
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.