Hi! I published a new blog post about “Why excepti...
# feed
l
Hi! I published a new blog post about “Why exception handling with Kotlin Coroutines is so hard and how to successfully master it!“. https://www.lukaslechner.com/why-exception-handling-with-kotlin-coroutines-is-so-hard-and-how-to-successfully-master-it/. I hope I can help a few people with this complex subject!
👍 13
j
There's a great article on this topic by Roman Elizarov: https://medium.com/@elizarov/kotlin-and-exceptions-8062f589d07
Exceptions should be handled by some top-level framework code of your application to alert developers of the bugs in the code and to restart your application or its affected operation. That’s the primary purpose of exceptions in Kotlin.
When you face an API that is using exceptions for conditions that are not logic errors for your code, then it is better to write a separate wrapper function that converts its exceptions to the appropriate return value and use this wrapper from your code. This way, your caller will have to handle the error condition right away and you avoid writing
try/catch
in your general application code.
Good insights. Basically, code that throws exceptions is brittle. The only exceptions you should be seeing are the "scream loudly" variety because some bug prevents the app from working properly. The only catch code that should be there is the bit where you basically scream loudly.
j
I found out the hard way earlier how exceptions can cancel coroutine scopes 🙂 I think the best way is to not throw any exception at all, but return Result objects. In this way you will never miss a thrown exception, as kotlin doesn't do typed exceptions and you will not be warned about any possible exceptions. Relying on catching exceptions is therefore very tricky and easy to forget. The only exceptions I do catch, is right when I call a framework that might throw one. Then I wrap it into a result object an be done with it.
o
Thanks for the post, IMHO exceptions and coroutines are easy to do wrong together, and having so many rules just indicates that. I don't have an alternative solution, for me using result object is cumbersome in many cases. I just think it prevent coroutines from being more widely adopted.
j
execeptions and coroutines are easy to do wrong together
the argument is that extensive experience with Java have shown that exceptions-based code is easy to do wrong. If you accept that premise there is no way you could add coroutines to the mix and make it hard to do wrong. The path recommended by Roman is solid IMHO. Money quote:
- no exception should be lost
- all bugs should get reported to developers.
- don’t use exceptions if you need local handling of certain failure scenarios in your code
- don’t use exceptions to return a result value
- avoid try/catch in general application code
- implement centralized exception-handling logic
- handle input/output errors uniformly at an appropriate boundary of your code.
👍 3