Kotlin

Exception Handling in Kotlin - Try, Catch, and Finally


Exception handling is an essential part of any programming language, and Kotlin provides robust mechanisms for handling exceptions gracefully. In this guide, we'll explore how to use try-catch blocks for exception handling and the role of the `finally` block.

Basic Exception Handling

Kotlin uses try-catch blocks to handle exceptions. Here's a basic example:

try {
    val result = 10 / 0
} catch (e: ArithmeticException) {
    println(`An arithmetic exception occurred: ${e.message}`)
}
    

In this example, a division by zero operation is attempted, and when an `ArithmeticException` is thrown, it's caught in the catch block.

Catching Multiple Exceptions

You can catch multiple exceptions using separate catch blocks:

try {
    val result = 10 / 0
} catch (e: ArithmeticException) {
    println(`An arithmetic exception occurred: ${e.message}`)
} catch (e: Exception) {
    println(`An exception occurred: ${e.message}`)
}
    

The `finally` block is used for code that should be executed regardless of whether an exception was thrown or not. It's often used for cleanup tasks:

try {
    // Perform some operations that may throw exceptions
} catch (e: Exception) {
    println(`An exception occurred: ${e.message}`)
} finally {
    // Cleanup code, e.g., close resources
}
    

Custom Exceptions

You can create custom exceptions by extending the `Exception` class or its subclasses:

class CustomException(message: String) : Exception(message)
try {
    // Perform some operations
    if (somethingWentWrong) {
        throw CustomException(`Something went wrong.`)
    }
} catch (e: CustomException) {
    println(`Custom exception: ${e.message}`)
}
    

Conclusion

Exception handling in Kotlin using try-catch blocks is crucial for writing robust and reliable code. It allows you to gracefully handle unexpected situations and ensure your application continues to run smoothly. The `finally` block is useful for cleanup tasks, and custom exceptions help you handle application-specific error scenarios.

Happy coding!

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.