Kotlin try-catch

Kotlin try-catch

In Kotlin, you can use a try-catch block to handle exceptions and errors that may occur during the execution of your code.

In this tutorial, we shall go through the syntax, examples, and an example for catching multiple exceptions.

Syntax of try-catch

The syntax of try-catch statement is given below.

try {
    // Code that might throw an exception
} catch (e: ExceptionType) {
    // Code to handle the exception
} finally {
    // Optional: Code that runs regardless of whether an exception was thrown or not
}

Let’s break down the components of a try-catch block:

  1. try: This block contains the code that you want to monitor for exceptions. If an exception occurs within this block, it will be caught by the associated catch block.
  2. catch: This block is executed when an exception of the specified type (ExceptionType) is thrown within the try block. You can catch specific exceptions, such as IOException, or you can catch more general exceptions like Exception if needed. Also, you can write more than one catch blocks, after a try block.
  3. finally (optional): This block is executed regardless of whether an exception was thrown or not. It’s often used for cleanup operations or to ensure that certain code always runs.

Kotlin Example for try-catch

In this example, we attempt to divide numerator value of 10 by denominator value of 0.

Main.kt

fun main() {
    val numerator = 10
    val denominator = 0

    try {
        val result = numerator / denominator
        println("Result: $result")
    } catch (e: ArithmeticException) {
        println("An arithmetic error occurred: ${e.message}")
    } finally {
        println("This block always executes.")
    }
}

Since division by zero is not allowed, it will throw an ArithmeticException. The catch block handles this exception, and the finally block always runs.

Output

An arithmetic error occurred: / by zero
This block always executes.

If you have other code that could throw another exception, then you have to replace ArithmeticException with the specific type of exception you expect to encounter in your code.

Kotlin Example try-catch with multiple catch blocks

In this example, we have a list of values, some of which can be parsed to integers, and some cannot. We use a for loop to iterate through the list and attempt to convert each value to an integer using toInt().

Main.kt

fun main() {
    val values = listOf("1", "2", "three", "4")

    for (value in values) {
        try {
            val parsedValue = value.toInt()
            println("Successfully parsed: $parsedValue")
        } catch (e: NumberFormatException) {
            println("NumberFormatException: '${e.message}' occurred for '$value'")
        } catch (e: ArithmeticException) {
            println("ArithmeticException: '${e.message}' occurred for '$value'")
        } catch (e: Exception) {
            println("Generic Exception: '${e.message}' occurred for '$value'")
        }
    }
}
  • If the value can be successfully parsed, it is printed as “Successfully parsed.”
  • If a NumberFormatException occurs (e.g., when trying to parse “three” as an integer), the code inside the first catch block is executed, and a message is printed indicating the specific exception and the value that caused it.
  • If an ArithmeticException occurs (which is unlikely in this context), the code inside the second catch block is executed.
  • If any other type of exception occurs, the code inside the third catch block (catching the more general Exception type) is executed.

Output

Successfully parsed: 1
Successfully parsed: 2
NumberFormatException: 'For input string: "three"' occurred for 'three'
Successfully parsed: 4

The catch blocks allow you to handle different types of exceptions in a tailored way, providing more specific error messages or taking different actions based on the exception type.

Summary

In this Kotlin tutorial, we have seen what a try-catch statement in Kotlin is, its syntax, and an example of how to use a try-catch statement to handle ArithmeticException when division by zero is attempted. Also, we have seen an example on how to catch multiple exceptions.