Kotlin Tutorial - 6 Exception Handling

nadirbasalamah

nadirbasalamah

Posted on October 6, 2021

Kotlin Tutorial - 6 Exception Handling

Exception handling is a mechanism to handle certain exception or error that occurred in a program or application so the program or application can be used normally although the exception is occurred.

Create an Exception Handling

In Kotlin, exception handling can be created using try catch block. The try block is used to execute a code that potentially could cause exception. The catch block is used to execute certain code if the exception occurred.

This is the basic syntax to create exception handling.

try {
    // code..
} catch (e: exception_type) {
    // code..
}
Enter fullscreen mode Exit fullscreen mode

This is the example of exception handling usage.

fun main() {
    try {
        val result = 9 / 0 // exception occurred here
        println("The result: $result")
    } catch (e: Exception) {
        // print out the exception message
        println("Error occurred: ${e.message}")
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Error occurred: / by zero

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the exception is occurred inside try block because the division operation with zero cannot be executed so the code inside catch block is executed.

If the exception is occurred in try block then the other codes is not executed.

try {
    val result = 9 / 0 // exception occurred here
    println("The result: $result") // this code is not executed
} catch (e: Exception) {
    // print out the exception message
    println("Error occurred: ${e.message}")
}
Enter fullscreen mode Exit fullscreen mode

The finally block is also available to execute certain code although the exception is occurred. This is the example of finally block usage.

fun main() {
    try {
        val result = 9 / 0 // exception occurred here
        println("The result: $result")
    } catch (e: Exception) {
        // print out the exception message
        println("Error occurred: ${e.message}")
    } finally {
        // this code is still executed
        println("I am done!")
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Error occurred: / by zero
I am done!

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the exception is occurred but the code inside finally block is executed.

If there are many catch blocks that handle exceptions, then the most suitable exception type inside catch block will be executed.

fun main() {
    try {
        val result = 3 / 0
        println("The result is: $result")
    } catch (e: ArithmeticException) {
        // this code is executed
        // because the most suitable exception type is ArithmeticException
        println("Error occurred in arithmetic: ${e.message}")
    } catch (e: Exception) {
        println("Error occurred: ${e.message}")
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Error occurred in arithmetic: / by zero

Enter fullscreen mode Exit fullscreen mode

Create Custom Exception

The exception can be created by using throw keyword followed with the exception type that will be used.

This is the example of using custom exception in pow() function.

fun main() {
    try {
        // use pow function
        val result = pow(2,-1)
        println("The result is: $result")
    } catch (e: ArithmeticException) {
        // if exception occurred
        // print out the exception message
        println("Error occurred: ${e.message}")
    }
}

// create pow function
fun pow(x: Int, y: Int): Int {
    if (y < 0) {
        // create custom exception
        throw ArithmeticException("y must be positive number!")
    } else {
        return Math.pow(x.toDouble(),y.toDouble()).toInt()
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Error occurred: y must be positive number!

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the exception is occurred because when the pow() function is called, the value for y parameter is equals negative number or 0.

The pow() function can be used if the value for y parameter is a positive number.

fun main() {
    try {
        // use pow function
        // with positive number
        val result = pow(2,3)
        println("The result is: $result")
    } catch (e: ArithmeticException) {
        // if exception occurred
        // print out the exception message
        println("Error occurred: ${e.message}")
    }
}

// create pow function
fun pow(x: Int, y: Int): Int {
    if (y < 0) {
        // create custom exception
        throw ArithmeticException("y must be positive number!")
    } else {
        return Math.pow(x.toDouble(),y.toDouble()).toInt()
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

The result is: 8

Enter fullscreen mode Exit fullscreen mode

Another way to create custom exception is creating a function that returns Nothing that means a function never return any value.

This is the example of create a function with Nothing return value. This function is used to create an exception.

fun main() {
    val username = "test"
    try {
        // perform simple validation
        if (username.length >= 6) {
            println("welcome!")
        } else {
            // if validation fails
            // the invalid function is called
            // as an exception
            invalid("username is invalid!")
        }
    } catch (e: Exception) {
        println("Error occurred: ${e.message}")
    }
}

// create an exception with invalid function
fun invalid(message: String): Nothing {
    throw Exception(message)
}
Enter fullscreen mode Exit fullscreen mode

Output

Error occurred: username is invalid!

Enter fullscreen mode Exit fullscreen mode

Based on the code above, the invalid() function is called as exception if the validation fails so the code inside catch block is executed to print out the exception message.

Sources

  • Learn more about exception handling in this link.

I hope this article is helpful for learning the Kotlin programming language. If you have any thoughts or comments you can write in the discussion section below.

💖 💪 🙅 🚩
nadirbasalamah
nadirbasalamah

Posted on October 6, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related