Kotlin Tutorial - 6 Exception Handling
Tags: kotlin, beginners, tutorial
Published: 2021-10-06 01:59:51

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..
}
```

This is the example of exception handling usage.

```kotlin
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}")
    }
}
```

Output

```
Error occurred: / by zero

```

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.

```kotlin
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}")
}
```

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

```kotlin
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!")
    }
}
```

Output

```
Error occurred: / by zero
I am done!

```

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.

```kotlin
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}")
    }
}
```

Output

```
Error occurred in arithmetic: / by zero

```

## 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.

```kotlin
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()
    }
}
```

Output

```
Error occurred: y must be positive number!

```

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.

```kotlin
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()
    }
}
```

Output

```
The result is: 8

```

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.

```kotlin
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)
}
```

Output

```
Error occurred: username is invalid!

```

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](https://kotlinlang.org/docs/exceptions.html).

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.