[Kotlin] How do I implement error handling using try-except blocks in Kotlin?

In Kotlin, you can implement error handling using try-catch blocks. The try block contains the code that may throw an exception, and the catch block handles the exception. Here's an example:

 1fun main() {
 2    try {
 3        // Code that may throw an exception
 4        val result = divide(10, 0)
 5        println("Result: $result")
 6    } catch (e: Exception) {
 7        // Handle the exception
 8        println("An exception occurred: ${e.message}")
 9    }
10}
11
12fun divide(a: Int, b: Int): Int {
13    return a / b
14}

In this example, the divide function tries to divide two numbers. Since dividing by zero is not allowed, it will throw an ArithmeticException. The try block in the main function calls divide and catches any exception that may occur. If an exception is thrown, the catch block will be executed, printing the exception message.

Output:

1An exception occurred: / by zero

You can have multiple catch blocks to handle different types of exceptions. The catch blocks are checked in order, and the first matching block will be executed. You can also have a catch block without specifying the exception type to handle all types of exceptions. For example:

1try {
2    // Code that may throw an exception
3} catch (e: IOException) {
4    // Handle IOException
5} catch (e: IllegalArgumentException) {
6    // Handle IllegalArgumentException
7} catch (e: Exception) {
8    // Handle any other exception
9}

Finally, you can also use the finally block to execute code that should always run, whether an exception occurred or not. For example:

1try {
2    // Code that may throw an exception
3} catch (e: Exception) {
4    // Handle the exception
5} finally {
6    // Code that will always run
7}

The finally block is optional, but if present, it will be executed regardless of whether an exception occurred in the try block or not.