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 }
//  throw exception if person.name is null   
val s = person.name ?: throw IllegalArgumentException("Name required")

runCatching() function

The runCatching() function allows catch and handle exceptions in the function style. It returns instance of Result class.

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

Result is a inline class that represents a success value or a Throwable value in case of an error. Some members of class are:

  • isFailure - true value indicates a failed outcome
  • isSuccess - true value indicates a success outcome
  • getOrNull() - returns the encapsulated value if this instance represents success or null if it is failure
  • exceptionOrNull() - returns the encapsulated Throwable exception if this instance represents failure or null if it is success
  • onSuccess(block) - performs the given block if this instance represents success, returns the original Result
  • onFailure(block) - performs the given block if this instance represents failure, returns the original Result

use() function

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

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

To use it you need jdk8, so make sure you add the appropriate standard library.

// implementation(kotlin("stdlib"))

withLock() function

The extension function withLock() replaces try-catch-finally construction for the ReentrantLock class.

    // do something