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 23.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 23.35  Invoking a method that throws an exception (Hero.kt)

@file:JvmName("Hero")

fun main() {
    ...
    adversary.offerFood()

    adversary.extendHandInFriendship()
}
...

Run this code, and you will see that a runtime exception is thrown. It is not wise to trust a monster. ...

Get Kotlin Programming: The Big Nerd Ranch Guide, 2nd 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.