Start Coding

Topics

Kotlin Exceptions

Exceptions in Kotlin provide a powerful mechanism for handling errors and unexpected situations in your code. They help maintain program flow and gracefully manage potential issues.

What are Exceptions?

Exceptions are objects that represent errors or exceptional conditions occurring during program execution. When an exception is thrown, it disrupts the normal flow of the program.

Try-Catch Blocks

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


try {
    // Code that might throw an exception
} catch (e: ExceptionType) {
    // Handle the exception
}
    

Common Exception Types

  • ArithmeticException: Thrown for arithmetic errors, like division by zero
  • NullPointerException: Occurs when attempting to use a null reference
  • IndexOutOfBoundsException: Thrown when accessing an array or collection with an invalid index

Throwing Exceptions

You can throw exceptions using the throw keyword:


fun divide(a: Int, b: Int): Int {
    if (b == 0) {
        throw ArithmeticException("Division by zero")
    }
    return a / b
}
    

Multiple Catch Blocks

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


try {
    // Code that might throw exceptions
} catch (e: ArithmeticException) {
    println("Arithmetic error: ${e.message}")
} catch (e: NullPointerException) {
    println("Null pointer error: ${e.message}")
} catch (e: Exception) {
    println("General error: ${e.message}")
}
    

Finally Block

The finally block is executed regardless of whether an exception occurs:


try {
    // Code that might throw an exception
} catch (e: Exception) {
    // Handle the exception
} finally {
    // This block always executes
}
    

Try as an Expression

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


val result = try {
    divide(10, 0)
} catch (e: ArithmeticException) {
    0 // Return 0 if division by zero occurs
}
    

Custom Exceptions

You can create custom exceptions by extending the Exception class:


class CustomException(message: String) : Exception(message)

fun validateAge(age: Int) {
    if (age < 0) {
        throw CustomException("Age cannot be negative")
    }
}
    

Best Practices

  • Only catch exceptions you can handle meaningfully
  • Use specific exception types when possible
  • Avoid catching Throwable or Error
  • Log exceptions for debugging purposes
  • Consider using Kotlin Nullable Types to avoid NullPointerException

Understanding exceptions is crucial for writing robust Kotlin code. They help manage errors effectively and improve the overall reliability of your programs.

Related Concepts