Kotlin throws Annotation in Exception Tutorial With Example

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

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.

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners