Kotlin throws Annotation in Exception Tutorial With Example

In this kotlin tutorial, we will learn about kotlin throws annotation in exception. We will learn how to use kotlin throws annotation? When should we use throws annotation in kotlin program? etc.

Getting Started

As we already know that all the exceptions in kotlin are unchecked exception. Developers who consume your code from java might not be aware that your function throws an error.

Let’s take an example,

Assume you have a function checkCharacter in Utils.kt file.

fun checkCharacter(letter: Char) {
    val result =
            if (letter in 'a'..'z')
                letter
            else
                throw IllegalArgumentException("A letter must be between a to z")

    print(result)
}

Above program throws an exception when you call it as checkCharacter(‘1’). This is because ‘1’ is not a letter from ‘a’ to ‘z’.

Now, we call this function from java class as

public void customJavaMethod() {
    Integer result = Utils.checkCharacter('a');
    System.out.println(result);
}

This works as expected in java. Compiler does not complain. However, if you want to inform java developer that functoin checkCharacter() throws an exception, you can do so using @Throws annotation to the function signature.

You can do it as below –

@Throws(IllegalArgumentException::class)            //@Throws annotation used to inform that this function throws exception.
fun checkCharacter(letter: Char) {
    val result =
            if (letter in 'a'..'z')
                letter
            else
                throw IllegalArgumentException("A letter must be between a to z")

    print(result)
}

If you want to use multiple exceptions with @Throws annotation, you can do write them separated by comma. For example,

@Throws(IllegalArgumentException::class, ArithmeticException::class)

Now, when java developer consume your code, they will have to modify their method as below –

public void customJavaMethod() throws IllegalArgumentException {
    Integer result = Utils.checkCharacter('a');
    System.out.println(result);
}

That’s end of tutorial on kotlin throws annotation.

Leave a Reply