Writing Swift-friendly Kotlin Multiplatform APIs — Part V: Exceptions

<p>The machine has just dispensed your expresso. You grab your cup, and, suddenly you notice a Macbook Pro with a Swift-logo sticker rushing in your direction. An angry face emerges from behind the laptop:<br /> <em>&ldquo;It&rsquo;s crashing!&rdquo;</em>. Your iOS teammate turns the screen at you, pointing to something that looks like assembly code. It takes a while for you to understand:&nbsp;<em>&ldquo;Ah! Why didn&rsquo;t you catch the exception?&rdquo;</em>.&nbsp;<em>&ldquo;Why didn&rsquo;t I catch the exception? Why didn&rsquo;t I catch the exception? How dare you say that?!&rdquo;.</em>&nbsp;Fuming, the developer&nbsp;<strong><em>throws</em></strong>&nbsp;&mdash; pun intended &mdash; the Macbook at you. You are clueless about what just happened.</p> <blockquote> <p>This article is part of a series, see the other articles&nbsp;<a href="https://medium.com/@aoriani/list/writing-swiftfriendly-kotlin-multiplatform-apis-c51c2b317fce" rel="noopener">here</a></p> </blockquote> <p>In order to explain the reason behind the wrath of your Swift colleague, let&rsquo;s remember something you did last summer:&nbsp;<strong>you wrote Java!</strong></p> <pre> import java.io.IOException; public class JavaReader { int read() throws IOException { throw new IOException(&quot;There&#39;s no data&quot;); } public static void main(String... args) { final JavaReader reader = new JavaReader(); try { int value = reader.read(); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } } }</pre> <p>If we rewrite this code again in&nbsp;<strong>pure</strong>&nbsp;Kotlin fashion it will be something like this:</p> <pre> import java.io.IOException class KotlinReader { fun read(): Int { throw IOException() } } fun main() { // This compiles fines, although not advisable val value = KotlinReader().run { read() } }</pre> <p>Did you notice the difference? In Java&nbsp;<code>IOException</code>&nbsp;is a checked exception. That means that you must either handle it with a&nbsp;<code>try-catch</code>&nbsp;block or declare the exception in the function signature.&nbsp;<a href="https://kotlinlang.org/docs/exceptions.html#checked-exceptions" rel="noopener ugc nofollow" target="_blank">Kotlin went away with checked exceptions</a>. Let&rsquo;s bring that to the multiplatform world</p> <p><a href="https://proandroiddev.com/writing-swift-friendly-kotlin-multiplatform-apis-part-v-exceptions-425998f579e1">Visit Now</a></p>
Tags: APIs Kotlin