0
0
KotlinHow-ToBeginner · 4 min read

Why Kotlin Has No Checked Exceptions Explained Simply

Kotlin does not have checked exceptions because it aims to keep code simple and readable by avoiding forced exception handling. Instead, Kotlin uses unchecked exceptions, letting developers decide when and how to handle errors without compiler enforcement.
📐

Syntax

Kotlin uses try-catch blocks to handle exceptions, but it does not require you to declare or catch specific exceptions in function signatures. This means you write code without throws declarations.

Example syntax parts:

  • try: Block where exceptions might happen.
  • catch: Block to handle exceptions if they occur.
  • finally: Optional block that always runs after try/catch.
kotlin
fun readFile() {
    try {
        // Code that might throw an exception
    } catch (e: Exception) {
        // Handle exception
    } finally {
        // Cleanup code
    }
}
💻

Example

This example shows how Kotlin handles exceptions without checked exceptions. The function readFile throws an exception, but it is not declared in the function signature. The caller decides whether to catch it.

kotlin
fun readFile() {
    throw IllegalArgumentException("File not found")
}

fun main() {
    try {
        readFile()
    } catch (e: IllegalArgumentException) {
        println("Caught exception: ${e.message}")
    }
}
Output
Caught exception: File not found
⚠️

Common Pitfalls

Because Kotlin does not force you to catch exceptions, you might forget to handle important errors, leading to crashes. Also, mixing Kotlin with Java code that uses checked exceptions can confuse developers expecting forced handling.

Always document which exceptions your functions might throw and handle exceptions thoughtfully.

kotlin
fun riskyOperation() {
    // Throws exception but no declaration needed
    throw RuntimeException("Something went wrong")
}

fun main() {
    // No compile error if we don't catch
    riskyOperation() // May crash if exception not caught
}
📊

Quick Reference

ConceptKotlin BehaviorJava Checked Exceptions
Exception DeclarationNo need to declare exceptions in function signaturesMust declare checked exceptions with throws
Exception HandlingOptional try-catch blocksMust catch or declare checked exceptions
Code VerbosityLess boilerplate, cleaner codeMore boilerplate due to forced handling
Interop with JavaUnchecked exceptions only, but can call Java checked exceptionsChecked exceptions enforced by compiler

Key Takeaways

Kotlin uses unchecked exceptions to keep code simple and readable.
You do not declare exceptions in function signatures in Kotlin.
Exception handling is optional, giving developers flexibility.
Be careful to handle exceptions properly to avoid runtime crashes.
Kotlin interoperates with Java but does not enforce checked exceptions.