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

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:
“It’s crashing!”. Your iOS teammate turns the screen at you, pointing to something that looks like assembly code. It takes a while for you to understand: “Ah! Why didn’t you catch the exception?”“Why didn’t I catch the exception? Why didn’t I catch the exception? How dare you say that?!”. Fuming, the developer throws — pun intended — the Macbook at you. You are clueless about what just happened.

This article is part of a series, see the other articles here

In order to explain the reason behind the wrath of your Swift colleague, let’s remember something you did last summer: you wrote Java!

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());
        }

    }
}

If we rewrite this code again in pure Kotlin fashion it will be something like this:

import java.io.IOException

class KotlinReader {
    fun read(): Int {
        throw IOException()
    }
}

fun main() {
    // This compiles fines, although not advisable
    val value = KotlinReader().run { read() }
}

Did you notice the difference? In Java IOException is a checked exception. That means that you must either handle it with a try-catch block or declare the exception in the function signature. Kotlin went away with checked exceptions. Let’s bring that to the multiplatform world

Visit Now

Tags: APIs Kotlin