Junior — Middle
Can you describe the features of exception handling in Kotlin?
sobes.tech AI
Answer from AI
In Kotlin, exception handling is similar to Java, but there are some differences:
- Kotlin does not have checked exceptions, so the compiler does not require mandatory catching or declaring exceptions.
- Exception handling uses try-catch-finally blocks, just like in Java.
- You can use try as an expression, meaning the result of the try-catch block can be assigned to a variable.
Example:
val result = try {
riskyOperation()
} catch (e: Exception) {
println("Error: ${e.message}")
null
}
- It is also possible to use the throw operator to throw exceptions.
- Kotlin supports creating custom exception classes by inheriting from Exception or RuntimeException.
Thus, Kotlin simplifies exception handling by removing the need to declare and handle checked exceptions.