https://kotlinlang.org logo
#coroutines
Title
# coroutines
c

ck

02/11/2019, 11:14 AM
Hi, what is the recommended way on Android to handle exceptions that occur inside
GlobalScope.launch
? A
CoroutineExceptionHandler
?
g

gildor

02/11/2019, 11:26 AM
Why not just use try/catch inside of launch?
c

ck

02/11/2019, 11:40 AM
Because I want to propagate the Exception to the calling function. i.e.
ClassA
calls
ClassB#functionA
and
ClassB#functionA
throws an Exception inside
GlobalScope.launch
which should be handled by
ClassA
. Instead the App crashes because the default
Thread.uncaughtExceptionHandler
is used.
d

Dico

02/11/2019, 12:13 PM
The exception cant be propagated to the caller because
launch
is non-blocking.
c

ck

02/11/2019, 1:09 PM
Thanks @Dico. Is there a recommended way to solve what I am trying to do (https://kotlinlang.slack.com/archives/C1CFAFJSK/p1549885230009800?thread_ts=1549883682.009500&cid=C1CFAFJSK) or should I try a different approach?
d

Dico

02/11/2019, 1:11 PM
I am personally confused with the exception handling stuff. I think the CEH might work though.
g

gildor

02/11/2019, 1:28 PM
But GlobalScope.launch is asyncronous background job in global scope, you cannot just propagate any error, exactly the same you have if start new thread that throws an exception
If you need exception handling on call site, why do you need launch In general, do you have some example of such code?
But in general yes, CEH will help in this case, same way as thread.uncaughtexceptionHandlet would help in case of thread, but in general this approach looks a bit hacky and such way to handle exceptions smells, so I would consider other options, but for sure it depends on your case
a

ansman

02/11/2019, 4:42 PM
If you want to to propagate exceptions to the caller you should use
async
over
launch
.
launch
is like fire and forget (though you can wait for it to complete)
g

gildor

02/11/2019, 5:13 PM
Or even suspend function
👍 1
4 Views