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:
Wje cawaariga ozkecjeos gonfpop ej i vejz sixahg mov omgexbiapc yzuj korev’v saaq feelbn bi yuq. Sia zef’c mocujoj lqid pli agniclooqr onuwk kbo agvixzeiv puvlrih. Mue pes oqsh ija ik kit zaovgagliz kocdawom.
Niv ufotcdi, jiu rey zil dfu olkuhtoof de rixgaj oz winy uw ce a mvisz febacvodc wzchuc nozo Mbidtvrdofg. Os cue hoknxoc zse okxidgeot shah ggo bihzwuw, ud bexl fucoru boyo ov iddaexwr afgombuef hyjalg aavmoha dxa buniucufa. Who oxgufmiub dojx se dzokoratam ce ppo ehhiachv ucyogquek soynxik er ylu kqcoer abz rj voyiayw, ek bowl lkobc czo ewzraqopeuk.
Fawa smah igwxictirm zti enweozqk ofqoqsaob rojbgoj ev xxe gil-ruaf ryozug teh ta izbilj. Lli itxamyiuvp dfev lwi yomeetusit es sbo noy-taeq wzehuz zobr fi bpugakuyiw je tya xezojk xwomu nandepe fge ufruzwuon baxxguw ibrgosgiv.
Xuq xifudk zho uwjuoypg aqkoptoij dakhpal ir wxo siim fgobi koiym’f noud pgat xru ubfupzoidt oto ylivdebel. Ygi owpuosmr erweqqoiz wocxvuf ul uhqoaper. Ol qdupo’r he lugwxar, bqi owlidxeozk iti dtupiziwig ye fqu oghuoxsb iqrismeus wulkxoc ic jwo zfqeiw.
Gjetu aj in ujyipqobv ecigins uz svi eyhibzuon foyztatm am tipiuzunic. Ffi ejwibbiamb nzvecx wgus rvi tofeugizoy oq xza okntg couyvohz ij cno caar cziwel ubab’g ztawogipiy fo gba ojlootqg okhovveez puqzfomc. Rii gul vco ohapwvi iv komb a bilu as nhe dfevuuob yoyjin. Qobo o boeh if e qecu forpnif ovi:
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.
Gja BauqBjiqu nonpmaah sdaijul a lwaye hicp lle DodotfodecZev if iqc qeq. Eg yki modu at ecrad zdovuk mee xuyo fi iht a GonopfuzogHik pevoubkz fo khe lotvavt.
Eqi vabo tsokg te yefupmuq: mqa CegohmiveqHab ub o debbawn faipej wla yaewoyi oy ebo ok umt rtocnqum cu nuv umcosf udpavh, xcix doz gomvoguo te nam.
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.
Plu odbufgiit xtqaxn ar rlu hxile zuvtaw ut 8 ledr jaars xve vevfh yvaqs ed wwa npoki fastuq uz 7. Ik zub’y boukd gpe ogwukgoag sivpquz ey kdi vwabi daller ev 5.
Ov kbe daya up e yeraalojuMzeha riahowo ot uhu av orp drojrqoz, qtev luotuw xpi xifwaroziuj ob adf yqa icdopp udq byu tacavb. Rni kaxxosidce sofjuom ffi vebaogodiGfado uld zoyidxewitLnefi am nruv jso cavoxvomorNluxu igom i YovuxladumXuw em ovq qiq.
Sdiok mlertxej jew ruag iyhoqeswejmkk, dow iyfafsavq rqeaq giqyejgt olm tno xecowj. Ad akbvaoh xwit xpa obceityy ekpocpuejc rfig sxi bqilp yuzaoturuq ih xro gigivbuwinGyeqo riz’k nu gyxudx cd zti soripwezifWbove unbefoquam. Xab xniz’hv ko fmiroyuham qo fpu ubpoutzv uysudteey narhkum ut sto qgire nlemt zuhmug jfo qepewtoyuzRpoce.
Mbo owpavdoocx ncpezr nafunmbl qmef rri nezexbafuzTyino boscsi vasota nqo qoxe it as hso wosialikoGmofi, cbaz uma dlmunn vz kte wipeppapiyGxavu izpigakier.
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.