Exceptions and Interoperability

The hero has taught the Jhava monster language, and the monster will now extend its hand in friendship … or maybe not. Add a method, extendHandInFriendship, to Jhava.java.

Listing 20.34  Throwing an exception in Java (Jhava.java)

public class Jhava {
    ...
    public void offerFood() {
        Hero.handOverFood("pizza");
    }

    public void extendHandInFriendship() throws Exception {
        throw new Exception();
    }
}

Invoke this method in Hero.kt:

Listing 20.35  Invoking a method that throws an exception (Hero.kt)

@file:JvmName("Hero")

fun main(args: Array<String>) {
    ...
    adversary.offerFood()

    adversary.extendHandInFriendship()
}

fun makeProclamation() = "Greetings, beast!"
...

Run this code, and you will see that ...

Get Kotlin Programming: The Big Nerd Ranch Guide, First Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.