ProgrammingBackend Developer

How does exception handling work in Kotlin? Describe the nuances, differences from Java, handling checked/unchecked exceptions, 'try', 'catch', 'finally', propagation, and best practices. Provide an example.

Pass interviews with Hintsage AI assistant

Answer.

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.

Key points:

  • try/catch/finally blocks allow you to catch and handle exceptions. The finally block is always executed, even if an exception is thrown.
  • Difference from Java: in Kotlin all exceptions are unchecked. This simplifies syntax but requires careful error handling.
  • Kotlin supports "return value" in the try block, i.e., try can be used as an expression that returns a result.
  • New idioms: it is recommended to avoid using try/catch for flow control — use them only for truly exceptional situations.
fun parseIntOrNull(str: String): Int? = try { str.toInt() } catch (e: NumberFormatException) { null }

Best practices:

  • Not to be used for controlling logic (flow control).
  • Use "resource management" with use for auto-closing (e.g., files).
  • Do not swallow exceptions with an empty catch.

Trick question.

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).

Examples of real errors due to lack of knowledge on the topic.


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.