Sobes.tech
Junior

How to handle exceptions in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, exception handling uses try, catch, and finally blocks.

fun divide(a: Int, b: Int): Int {
    try {
        // Potentially dangerous code
        return a / b
    } catch (e: ArithmeticException) {
        // Handling specific exception
        println("Error: division by zero!")
        return 0
    } catch (e: Exception) {
        // Handling general exceptions
        println("An unknown error occurred: ${e.message}")
        throw e // Rethrow exception if necessary
    } finally {
        // Code that runs in any case (regardless of exception)
        println("Resource cleanup or other final actions")
    }
}
  • The try block contains code that might throw an exception.
  • The catch block is used to catch and handle exceptions. Multiple catch blocks can be used to handle different exception types. Exceptions are caught in the order they are declared.
  • The finally block contains code that always executes, regardless of whether an exception was thrown and caught. This block is often used for resource cleanup.

Unlike Java, Kotlin does not have checked exceptions that require mandatory handling. All exceptions in Kotlin are unchecked.

To throw exceptions, the throw keyword is used:

fun validateAge(age: Int) {
    if (age < 0) {
        throw IllegalArgumentException("Age cannot be negative")
    }
    // ...
}

You can also use standard exception classes from the standard library or create your own by inheriting from Exception or RuntimeException.