Kotlin is a language that is designed to maintain interoperability with Java code. The following example shows a nuance that we should take into account when we invoke Kotlin code from Java code. Let's create a simple Kotlin function that throws an exception:
fun testMethod() {
throw IOException()
}
This function can be called from Java code like this:
public class Example5 {
public static void main(String[] args) {
Example5Kt.testMethod();
}
}
And this code can be compiled. This behavior can be unexpected for a Java developer who is used to dealing with checked exceptions. See what happens if we write something like this:
public static void testMethod() {
throw new IOException();
}
The compiler will show the following error:
Error:(11, 9) java: unreported exception java.io.IOException; must be caught or declared to be thrown
To fix this error, we have to add the @Throws annotation, as follows:
@Throws(IOException::class)
fun testMethod() {
throw IOException()
}
Now, we have to handle an exception that can be thrown by the testMethod function in Java code:
public static void main(String[] args) {
try {
Example5Kt.testMethod();
} catch (IOException e) {
e.printStackTrace();
}
}