Recover in Kotlin

Kotlin provides a way to recover from exceptions using try-catch blocks. This is similar to Go’s recover functionality, allowing you to catch and handle exceptions that would otherwise crash the program.

An example of where this can be useful: a server wouldn’t want to crash if one of the client connections exhibits a critical error. Instead, the server would want to close that connection and continue serving other clients.

import kotlin.Exception

// This function throws an exception
fun mayThrow() {
    throw Exception("a problem")
}

fun main() {
    try {
        // The try block contains code that might throw an exception
        mayThrow()
        
        // This code will not run if mayThrow() throws an exception
        println("After mayThrow()")
    } catch (e: Exception) {
        // The catch block is executed if an exception is thrown in the try block
        // The caught exception is available in the variable 'e'
        println("Caught an exception. Error:\n ${e.message}")
    }
}

When you run this program, you’ll see:

$ kotlin recover.kt
Caught an exception. Error:
 a problem

In this example, the mayThrow() function throws an exception. The main() function calls mayThrow() inside a try block. When the exception is thrown, execution immediately jumps to the catch block, where we print out the error message.

The code after the mayThrow() call in the try block is not executed because of the exception. This is similar to how in the Go example, the code after the panic is not executed.

Unlike Go’s defer and recover, which are used specifically for panics, Kotlin’s try-catch is a more general mechanism for handling exceptions. It can catch any type of exception, not just panics.

In Kotlin, you can also use finally blocks to ensure that some code is always executed, whether an exception was thrown or not. This can be useful for cleanup operations.

try {
    mayThrow()
} catch (e: Exception) {
    println("Caught an exception: ${e.message}")
} finally {
    println("This will always be executed")
}

This exception handling mechanism allows your program to gracefully handle errors and continue execution, rather than crashing abruptly.