Custom Errors in Kotlin

Custom errors in Kotlin are typically implemented using exception classes. Here’s an example that demonstrates a custom error type and its usage:

import java.lang.Exception

// A custom error class usually extends Exception
class ArgError(val arg: Int, message: String) : Exception(message)

fun f(arg: Int): Int {
    if (arg == 42) {
        // Throw our custom exception
        throw ArgError(arg, "can't work with it")
    }
    return arg + 3
}

fun main() {
    try {
        f(42)
    } catch (e: ArgError) {
        // In Kotlin, we can directly use the caught exception
        println(e.arg)
        println(e.message)
    } catch (e: Exception) {
        println("err doesn't match ArgError")
    }
}

In this example, we define a custom ArgError class that extends Exception. It includes an arg property and a message, which are both passed to the constructor.

The f function demonstrates how to throw this custom exception when a specific condition is met (in this case, when the argument is 42).

In the main function, we use a try-catch block to handle the exception. Kotlin’s exception handling is more straightforward compared to Go’s error handling:

  1. We don’t need to explicitly check if an error occurred after calling a function. Instead, we use a try-catch block.
  2. In the catch block, we can directly access the properties of our custom exception.

When you run this program, it will output:

42
can't work with it

This demonstrates that our custom exception was caught and we were able to access its properties.

In Kotlin, we don’t have an exact equivalent to Go’s errors.As function. However, the type-based catch blocks in Kotlin serve a similar purpose, allowing us to handle different types of exceptions differently.

Kotlin’s exception handling mechanism provides a robust way to deal with errors, allowing for custom error types and easy access to error details when exceptions are caught.