Exceptions

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

All exception classes inherit the class Throwable. Every exception has a message, a stack trace, and an optional cause. Although you can use any Java exception class, Kotlin does not have checked exceptions.

The throw allows you to throw exception. It can be used as an expressions.

val s = person.name ?: throw IllegalArgumentException("Name required")

The try,catch, finally keywords allow you to catch and handle an exception.

There may be zero or more catch blocks. finally block may be omitted. However, at least one catch or finally block should be present.

try {
    // some code
    if(cond) 
        throw IllegalArgumentException("wrong argument")
} catch (e: SomeException) {
    // handler
} finally {
    // optional finally block
}

try-catch is an expression. It returns last value from <try-block> or <catch-block>.

val a: Int? = try { 
        parseInt(input) 
   } catch (e: NumberFormatException) { null }
   
val s = person.name ?: throw IllegalArgumentException("Name required")

functions

The runCatching() and onFailure() functions allow catch and handle exceptions in the function style.

runCatching {
    // ...
    someCode(arg)
}.onFailure { // it: Throwable ->
  when (it) {
      is IllegalArgumentException -> {
          handleIncorrectArg()
      }
      is IllegalStateException -> {
          handleWrongState()
      }
      else -> throw it
  }
}

The extension function use() for the Closeable interfaces replaces the try-with-resources statement of Java.

FileWriter("demo.txt")
    .use { it.write("Hello world!") }

The use() extension function for the AutoCloseable interface is available for jdk8.

// implementation(kotlin("stdlib"))
implementation(kotlin("stdlib-jdk8"))

The extension function withLock() for the ReentrantLock class replaces try-catch-finally construction, where lock in <finally-block> will be unlocked.

lock.withLock{
    // do something
}