Kotlin implements exception handling similarly to Java, but with important differences. In Kotlin, familiar constructs try, catch, and finally are used, however, the principal difference is that Kotlin does not have checked exceptions. This means that all exceptions (runtime errors) are considered unchecked — they do not need to be declared in the function signature or explicitly caught.
finally block is always executed, even if an exception is thrown.try block, i.e., try can be used as an expression that returns a result.try/catch for flow control — use them only for truly exceptional situations.fun parseIntOrNull(str: String): Int? = try { str.toInt() } catch (e: NumberFormatException) { null }
use for auto-closing (e.g., files).In Kotlin, do you need to specify in the function signature which exceptions it throws (like in Java — via throws)?
Correct answer: No, Kotlin has no mechanism for checked exceptions. All exceptions are unchecked. There is no throws syntax in the function signature (the exception is the @Throws annotation for compatibility with Java, only for interop).
Story
On the project, Java code using checked exceptions (e.g.,
IOException) was migrated. After migration to Kotlin, the developer forgot to handle exceptions when working with files — the application started crashing on real files because no one was handling IO errors, assuming that the compiler would warn like in Java.
Story
One team member mistakenly used try/catch for flow control, slowing down log parsing (caught NumberFormatException for each invalid string — performance drastically dropped on a large volume of data).
Story
In a project for JVM, Java code that declared checked exceptions (
throws) was called through Kotlin. The Kotlin code did not handle exceptions, thinking that "everything is unchecked" — as a result, a critical error went unnoticed until a production incident occurred.