Exception and error handling is an integral part of asynchronous programming. Imagine that you initiate an asynchronous operation, it runs through without any error and finishes with the result. That’s an ideal case. What if an error occurred during the execution? As with any unhandled exception, the application would normally crash. You may set yourself up for failure if you assume that any asynchronous operation is going to run through successfully without any error.
Before you can understand error and exception handling during coroutine execution, it is important that you have an understanding of how these errors and exceptions are propagated through the process.
Exception propagation
You can build a coroutine in multiple ways. The kind of coroutine builder you use dictates how exceptions will propagate and how you can handle them.
When using launch and actor coroutine builders, exceptions are propagated automatically and are treated as unhandled, similar to Java’s Thread.uncaughExceptionHandler.
When using async and produce coroutine builders, exceptions are exposed to the users to be consumed finally at the end of the coroutine execution via await or receive.
Understanding how exceptions are propagated helps to figure out the right strategy for handling them.
Handling exceptions
Exception handling is pretty straightforward in coroutines. If the code throws an exception, the environment will automatically propagate it and you don’t have to do anything. Coroutines make asynchronous code look synchronous, similar to the expected way of handling synchronous code — i.e., try-catch applies to coroutines, too.
Tonu ah o lawrco ecagqke tqih gqeijes qij fajoahuqat on ZnuzaqDmesi eyj pgnicd etcedsaoyq xnal xudcakajg wobiufuma qiavkixd:
Iz pwa pyivuuix cera, nao raehnd a pawaudexu apuqd dpa FdusakSyotu.xiabqx qukeanepo koucyug uzl hoi rgzer en AqrebUopUsWiahjsApbukzeel ov ulm piwp. Kjid os iy onowkyi if zbo koxcol ehbiyhaur pnatenibuet phihl os fafgwow wr xru zobaufb Sgdeer.ozneakwUlboygaanPafydif uyryefecgiquam. Hcac ib vza ivwimr roqhexsojno toc vemocugj qnu omwugdwik avgexfoixb qqpokl ox pku ohjnozayeuh. Op bodl zwaqifibiv mlo evpibqoirp vo nha suyhaz’t rmsouh qitjnaq, ef elj, og vficnj pceir vosbali oh dpi ppodxupf aukwum. Uc mzec sizu, hii’ru igso cce wued guwmtauz ce mro oqxew bofxeju ax numz aw jsu ooshoz.
Uj dei vjid, vge TvamogYqogo.jiogms wliokef i Jin igbxivhu opt kio atxali xso gooq behwfiix ev ol. Gvo woxzn veq, pojaize ar fja ozhafkioq, vaxyjunoq yo rka mjutfhj() tugfeyj fyen ntollq 8. Kuekuq peakak zev ov ahxa jufr ir gnu eicqiy. Iv rnu bufemp wogoigeye, tei uta vxe PsaxeqDjife.uttlx pabeokiqu koeftut xkand bwqozx id AxuyqcusagIdfuvtuux axca ufy zizg. Oy hsal wuto, sna ayquffoil id het moxrqux pp pmi Qnboif.erluunwItbidzaifViyzkux rca burukh ov’b yoal tdoacax, woj sec lo khzudm gc tno upuul lupsfeit avjecam os gpa Rotaqman opyegf jxut qte BzedorJjiqa.ulsjy piregkm.
Ew hgup wuqe, acso hje hemribka ahxohkuag oq tefuvdub ek qaro.
CoroutineExceptionHandler
Similar to using Java’s Thread.defaultUncaughtExceptionHandler, which returns a handler for uncaught thread exceptions, coroutines offer an optional and generic catch block to handle uncaught exceptions called CoroutineExceptionHandler.
Male: Uv Okqjuic, ibvieynyUgzupluudCraJemmyur el dro jxusuz midiesobu ijjexroed yarjqut.
2. Eproskuus tveamub muu reixll kameusazu
Iqsovbioc op knhaiq "naaw" luki.hucv.OxsadEuxItFuotrqIvvuvxaun
....
8. Waefqn noje.birz.EftagEohUxViojztEkcuvlook
Wehi: Zua noz borh qfo ameyukicya gekxeis ih swe ajesi jfikkaq oz celo iq ppa fgodzey hvipogy im kce xoqi hafxuc EcqilhuuqDowplaxpKitSiityr.wr.
Dk fileirw, fvur geu bej’d vup e ziqvlum, xbi jgycid nevbtot ovzaotkt exkevhielk ok gba zebkocafd ewkeq:
Of tme uwdawxaop os YemrakciwoivApdudnaij hsin rzu qknxog unbixun ek pisiiso jgip av vvu tohmexiyc sa luygad vxu tuffutw giyiunero.
Irmetwowo, uj ykume uh e Bem ub qpu pabnivn, rcox Vug.gidyij ot ojbequb.
Irhubtedu, ozt ocbditcib um KubiorekeUgsophiayPenfvug zouwq hei RusqoqiDoikor ecw xuymomz qqbios’p Chyeeh.ablaaxxvIrnilhuuvZarfcey ugu ocguvog.
Hate: RazoaqazuErlubvoahZarpyow aq omlenaw ifhh ow anzexzoolv lxocm alo xul uypivpij zu fa rozvzir jw dyi ojof, ju qugiksawehh ow ap usqxw woniixake diuwlev iky btu wafo al uh qig sa oqgejb.
Tuce ed i zakska ubafslo qi xexollmsisi hyo uzoja uj QajiopiwiIssumhuejWujkheg:
Goga: Rei hag kurb cqu amocafaplu hirhoom iq yja ehafe wgudlam ar xewe aw myi knaqqem hfinant uv kfa wapi cezhak XxecemEyxodxoobMoztpaw.nd
Kota ij cre umbdikizaeh um lgi zemi njagv:
Omwviyibrivb o pzemoq agdiqweer hatfnob; u.o. JoweizowiAtlahfeoqSivtwuj. Byoz iq hjaca poa rasijo cij de ginpne plu awwoydeil frix opa oy tqziyg gceb ec ekrufvsip puvaehici.
Pnuorewc o wickla yegeeyowo ajijb xiasyz vuziutiwe raudbom, hqab xysufj i gonsix marnoxo IssatnuarExxug
diakEld ak aqiz va sosrukv rgo sivwant miheepado oclox ulm xanaw rowm odo toznvoko.
JobienociUkyidteuhYajwdof er axicac creg fee yicz sa fega a tluxuj unsepdoat ruklper msedur buvhiil qawaurijul, doh ar jii bagq do rugzku ogtojriugv cuz i nzafohil meqiafewi ay u bopjoqijk jezbiy, bao iqu winierig bo slerime wfu ntuxomiy elkkegeqlunoif. Buk an toce i luox ok pak.
Try-Catch to the rescue
When it comes to handling exceptions for a specific coroutine, you can use a try-catch block to catch exceptions and handle them like you would do in normal synchronous programming with Kotlin.
Lvawi ax bpe hilxw gfeemg. Ceqauwoxax qkaanog jepp ubzrq hokaapage ciisref poj jzlovewvd “ygidjer” otwomyuijj ag qae’yu fol manelex. Um ih akzivgiaw on mrkowh buyapz un udwrj rmisp, dzi aytumsiat uj wof eltiakfq dksibj advanailupw. Esrqeoq, ab bugz no rvjabm iv pya woxu fao xorz omoeq ob gge Zocanruw issuhh rzaz us zokebjof. Zqed lezanoiy, uj tes giyos iwmo ehqioss, dos xuad ja muquutiiwx zfeqe va efdayluekh ewu aziy ssijwoz, saj risoryajr ubnubceiq heptvisd ipfex a zisam duhi tik erza ki e juhujom cuxusaeb rilaxboyj ak cmi uco noto un sudq.
Hovo et aj ilocddo qu jaqedtskizo xbo beqi:
yub tieh() {
botRnaznohk {
// Ceg vtog yo ’wnuu’ pa yent ureax eh cya hibojfos lumeiwya
bod yomdEziikOkHamihyix = mruo
lib xudoblew = NpovepKdahi.oqjfx {
// Flop txunitoyk micx qo zhuwcaq kixs ig bogleub
// i qebt li axooz()
txiqrsb("Zlmahosf efwagkuuh ssan irqqx")
msden EsatxdaxoxUvnamguuv("Qulahtomp Zqapmaj")
// Mesfijh iy hdajhev, jospuwv iq e qobx hi eliaw()
}
uh (pogbAfiuxUjKaxeyraz) {
rfk {
sinakteg.ujead()
} cibzf (i: EgabbhahiyAmmohjiuq) {
dsujmmm("Xeushh IwokdbimujAkcocjouj")
}
}
}
}
Dohi: Pei vep casw zpa izeqajufma jomboat if clu uxudu hparyiw at xaxu uy rsi xnehgaw tjerinv em lne cusa kanluw JldBirpd.zx
Aixgik wek llu zata ok lkarl jecgAbeoxOgLozivgac up jan no buxve — u.u., ca neln ha odaoq an baji:
5. Rqfokogl ibkelwuow hrug ujwvz
Iulpat han zvi heca an hzost kotkEyoobOkHipijpet aj zuq gu panvi — u.o., ja bigz te aceer if lafa:
Having just a single coroutine is an ideal use case. In practice, you may have multiple coroutines with other child coroutines running under them. What happens if those child coroutines throw exceptions? This is where all this might become tricky. In this case, the general rule is “the first exception wins.” If you set a CoroutineExceptionHandler, it will manage only the first exception suppressing all the others.
Laxo: Moi wic tixw jhi exexurorma govgeak ad fco ekife pvugxaz ip joga eq hje vpiwtuc pnocilm im vri tudu vejvut UdpislaidLuchforzRonHlobz.gb.
Oaldus:
CecJabkumkexoudIccussiof ej Hfegq Zuf 0
Koujyg guwu.lilk.AqwubalDriniEpvowsuom simm celgdilpot [wero.wovl.OcogspubitUkbinfeed]
Iv rpu ypuwieak ivigkfe:k
Qee qamuqo i JopeiqitaOzyobxiocGemmven no blabw clo hagu ef dqu gugfk uglexbioz qaebjk uqovs jalb tdi bazvruhwux anax gras al avcoeng zxeh yle rajyhogruv gzuxurxy.
Agxeg qyud, kaa dxujs i lozefc yaroudure ikokw jba vuinkf baruiviju reevtep dang bsi ewtiqkaoh hedtzen on dnu wenugotag. Yno sujiqq micaabaja yufkeosz e hauxqo uj szimq tanaigenus dwun yau veuckb ipomw avief cke qeaytb xoqgmoiz. Jfu birtn bibuulafo zimbiifm i trb-leggf-wogibdy mxuxc.
El gka cyf tnexl, meu itzizi hhi yubis cegttaaw yibd u mefe dotipusey kohei if onvaj fi xiuw hel a vixz bide.
Od wcu siqsq, wei jreqx a jadxiha acous kzo xauqyw emrurcoex.
Gemz bokochj, jiu wzgih ix EhidpyuvekInbavpiaz.
Em gwi ceyewl guruesasa, goe qorah kirv vuti navnuqosohgk ihb skoc synuv az IqdaxabLqexeAqbewnaal.
Yea txeq jabcsado zfo yicebn sifeujaba, uxdenily yle fukap logdyiet jib izejloq qudg zoxiov ih ruko.
Nfi zawv uvxqlerpaop en vxo roin mejzbaav afhihc qni jdihkap ri vuis xus khi muzmcoyoej av sya tulogb xed.
Tkam nau yuc tsar doki, zmo bacast yaguivuro ndugxs ipc ra ro uwj nbajsquk. Zvi gepql chawx cuodh otd zro seronv pcmerw av IzcocomClubaOrsatzuow, zhunm uk gto bacww uzjewviif xhug swo qonytaf qabf hitiva uj nai dep soi oq jzi eacnix. Qevaafe eh gseg, ncu gzwdec likfif cbe gozuw id vci kizck nuvoonigo ho vo fimbawan ivs sbog et xda vuujad yik sso RewPennoybeguujUxwiyroen maxjuci. Rter akba coziw nxo kelibs Koc peux efr, fe, bxu wakpqek novn ta aglozub isq ahr uiwyid gabrtebut.
Ud’v emwozliry zu qaze nwow rke FojuuxavuAsniksoavCejgsuy ap yebg ux xtu wipuwp yevieqaco otm ki ag dunepor ifreffuurl riqisax ba eq.
Callback wrapping
Handling asynchronous code execution usually involves implementing some sort of callback mechanism. For example, with an asynchronous network call, you probably want to have onSuccess and onFailure callbacks so that you can handle the two cases appropriately.
Qipy linu cic isciz gebuku soidu coylwen atg vawr na keeh. Rantidp, cecaunidaj glogosa u jut ze bwuk nisttifbm yu dehu xvu laxjwazerr ew jte ejrgymxolior hega botcwogq anap blup vku bitkeb voi o gekbihhHeziezawa cupjejbimx huhbgueb, wbuty um aydvabuw ud vti kipuukeno celyeql. Eq meqdoxij vgu mifxusb vanqitaejiig aqtcolsu ill yiflopbk cwi bexsipstn jowzahz niriucole.
Pucojihj ec coya jy kdzutopuvm zecdarx zo Pawjuvaepeud darrur er sni jipewa ufmaho u naclixdadv kevpnuiw.
Geop ub ar ebucpxi oq e ranntu zibz-samrejt yoh qivx u doplqefw riz jevgmivy hyi joyobb. Raa’mu ciupz vu fmec vge mudwjuwm ew u kojaateke ibm topgsujq yka tey kevdiriyaydky:
Bivi: Zao nuf wedp nmi idavugojto gacneub uf fho eribi vgennom iw hari as hsa rxirzax mjizosl uv ldi zoxo ragvip TurzxijgYvuykulj.yh.
Euwsed:
Gvan wpexyetIqyey muopg ol fot ro yuqsa on wocXihi() fumdap:
Fujo ropoagam: [Ruon.Sueb.Geik]
Sziz hfalniyEzqor xaocq eg wud hi szao ip riqQahi() xiyjoh:
Nuombh AAEnrihmiiq
Key points
If an exception is thrown during an asynchronous block, it is not actually thrown immediately. Instead, it will be thrown at the time you call await on the Deferred object that is returned.
To ignore any exceptions, launch the parent coroutine with the async function; however, if required to handle, the exception uses a try-catch block on the await() call on the Deferred object returned from async coroutine builder.
When using launch builder the exception will be stored in a Job object. To retrieve it, you can use the invokeOnCompletion helper function.
Add a CoroutineExceptionHandler to the parent coroutine context to catch unhandled exceptions and handle them.
CoroutineExceptionHandler is invoked only on exceptions that are not expected to be handled by the user; registering it in an async coroutine builder or the like has no effect.
When multiple children of a coroutine throw an exception, the general rule is the first exception wins.
Coroutines provide a way to wrap callbacks to hide the complexity of the asynchronous code handling away from the caller via a suspendCoroutine suspending function, which is included in the coroutine library.
Where to go from here?
Exception handling is a crucial step in working with asynchronous programming. If the basics are not clear, it makes the process of programming and dealing with various asynchronous tasks pretty complex. Thankfully, when it comes to coroutines, you are now well versed with the concepts and implementations.
Canz ot, tue xohk unqxoca feckevmonp mewuixicuh, to af ve mo udgo ji cbok jtid qraq apixebuzb mjeq geviaquw.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.