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
        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 { 
   } catch (e: NumberFormatException) { null }
val s = person.name ?: throw IllegalArgumentException("Name required")


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

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

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

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

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

// implementation(kotlin("stdlib"))

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

    // do something