Kotlin throw Exception Tutorial

In this section, we will learn how to throw an exception in Kotlin.

Note: we’re assuming you’re already familiar with the exception handling in Kotlin.

What does throw exception mean in Kotlin?

The throw keyword is a way of throwing exception manually in a program.

This is especially useful when your program reached to a point where it can’t run the normal flow because of a wrong input, a missed connection or anything that causes severe damage to the flow of the program! So there’s no choice but to throw an exception and alert users about the possible solution.

How to throw exception in Kotlin? (Kotlin throw Keyword Syntax)

This is how we can throw an exception in Kotlin:

throw ExceptionClass(“Message”)

To throw an exception, we start with the keyword throw.

Then, on the right side of this keyword, we put an object that represents the exception!

Note that in order to create an exception object, we need to call a class that inherits the Throwable class. For example, the Exception class is an example that could be used to create an exception object from.

Also, as the argument of the constructor for such type of classes, we need to pass a string value that explains the reason of exception. We can then use the message property to access this value in the catch handlers.

Note: you can create your own exception class and use it to create an exception object! This is explained in the Kotlin Custom Exception section.

Example: throwing exception via throw keyword

fun main(){
    checkAge(16)
}

fun checkAge(age:Int){
    try{
        if (age <18){
            throw IllegalArgumentException("Under legal age!")
        }else{
            println("Access granted!")
        }
    }catch (e: IllegalArgumentException){
        println(e.message)
    }
}

Output:

Under legal age!
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies