Kotlin Try Catch

Introduction

Exception handling in Kotlin is essential for writing robust applications. The try-catch block is used to handle exceptions, ensuring that the program continues running even when an error occurs.

Basic Try-Catch Syntax

The try block contains code that might throw an exception, and the catch block handles the exception.

Syntax

try {
    // Code that may throw an exception
} catch (e: ExceptionType) {
    // Code to handle the exception
} finally {
    // Optional: Code that will always execute
}

Example

fun main() {
    try {
        val result = 10 / 0
        println("Result: $result")
    } catch (e: ArithmeticException) {
        println("Exception caught: ${e.message}")
    } finally {
        println("Finally block executed")
    }
}

Explanation:

  • try { ... }: Contains code that may throw an exception.
  • catch (e: ArithmeticException) { ... }: Catches the exception and handles it.
  • finally { ... }: Contains code that will always execute, regardless of whether an exception is thrown or not.

Output:

Exception caught: / by zero
Finally block executed

Multiple Catch Blocks

You can use multiple catch blocks to handle different types of exceptions.

Example

fun main() {
    try {
        val numbers = listOf(1, 2, 3)
        println(numbers[5])
    } catch (e: IndexOutOfBoundsException) {
        println("Index out of bounds: ${e.message}")
    } catch (e: Exception) {
        println("General exception: ${e.message}")
    } finally {
        println("Finally block executed")
    }
}

Explanation:

  • catch (e: IndexOutOfBoundsException) { ... }: Catches IndexOutOfBoundsException.
  • catch (e: Exception) { ... }: Catches any other exceptions that are not caught by the previous catch block.

Output:

Index out of bounds: Index 5 out of bounds for length 3
Finally block executed

Throwing Exceptions

You can throw an exception explicitly using the throw keyword.

Example

fun main() {
    try {
        checkAge(15)
    } catch (e: Exception) {
        println("Exception caught: ${e.message}")
    }
}

fun checkAge(age: Int) {
    if (age < 18) {
        throw IllegalArgumentException("Age must be at least 18")
    }
}

Explanation:

  • throw IllegalArgumentException("Age must be at least 18"): Throws an IllegalArgumentException if the age is less than 18.

Output:

Exception caught: Age must be at least 18

Try as an Expression

In Kotlin, try can be used as an expression, returning a value.

Example

fun main() {
    val result = try {
        val number = "10a".toInt()
        number
    } catch (e: NumberFormatException) {
        -1
    }
    println("Result: $result")
}

Explanation:

  • val result = try { ... } catch (e: NumberFormatException) { ... }: Uses try as an expression to return a value based on whether an exception is thrown.

Output:

Result: -1

Custom Exceptions

You can create custom exceptions by extending the Exception class.

Example

fun main() {
    try {
        validateName("")
    } catch (e: InvalidNameException) {
        println("Exception caught: ${e.message}")
    }
}

class InvalidNameException(message: String) : Exception(message)

fun validateName(name: String) {
    if (name.isEmpty()) {
        throw InvalidNameException("Name cannot be empty")
    }
}

Explanation:

  • class InvalidNameException(message: String) : Exception(message): Defines a custom exception class InvalidNameException.
  • throw InvalidNameException("Name cannot be empty"): Throws the custom exception if the name is empty.

Output:

Exception caught: Name cannot be empty

Example Program with Try-Catch

Here is an example program that demonstrates various aspects of exception handling using try-catch in Kotlin:

fun main() {
    // Using try-catch-finally
    try {
        val result = divide(10, 0)
        println("Result: $result")
    } catch (e: ArithmeticException) {
        println("Exception caught: ${e.message}")
    } finally {
        println("Finally block executed")
    }

    // Using custom exception
    try {
        validateAge(15)
    } catch (e: InvalidAgeException) {
        println("Exception caught: ${e.message}")
    }

    // Using try as an expression
    val number = try {
        "123a".toInt()
    } catch (e: NumberFormatException) {
        -1
    }
    println("Parsed number: $number")
}

fun divide(a: Int, b: Int): Int {
    return a / b
}

fun validateAge(age: Int) {
    if (age < 18) {
        throw InvalidAgeException("Age must be at least 18")
    }
}

class InvalidAgeException(message: String) : Exception(message)

Output:

Exception caught: / by zero
Finally block executed
Exception caught: Age must be at least 18
Parsed number: -1

Conclusion

In this chapter, you learned about exception handling in Kotlin using try, catch, and throw keywords. You also learned how to create custom exceptions and use try as an expression.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top