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>“It’s crashing!”</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: <em>“Ah! Why didn’t you catch the exception?”</em>. <em>“Why didn’t I catch the exception? Why didn’t I catch the exception? How dare you say that?!”.</em> Fuming, the developer <strong><em>throws</em></strong> — pun intended — 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 <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’s remember something you did last summer: <strong>you wrote Java!</strong></p>
<pre>
import java.io.IOException;
public class JavaReader {
int read() throws IOException {
throw new IOException("There's no data");
}
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 <strong>pure</strong> 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 <code>IOException</code> is a checked exception. That means that you must either handle it with a <code>try-catch</code> block or declare the exception in the function signature. <a href="https://kotlinlang.org/docs/exceptions.html#checked-exceptions" rel="noopener ugc nofollow" target="_blank">Kotlin went away with checked exceptions</a>. Let’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>