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.
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.
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
}
ArithmeticException
: Thrown for arithmetic errors, like division by zeroNullPointerException
: Occurs when attempting to use a null referenceIndexOutOfBoundsException
: Thrown when accessing an array or collection with an invalid indexYou 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
}
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}")
}
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
}
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
}
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")
}
}
Throwable
or Error
NullPointerException
Understanding exceptions is crucial for writing robust Kotlin code. They help manage errors effectively and improve the overall reliability of your programs.