Kotlin has no Java-style multi-catch (catch (IOException | NumberFormatException e)). Catch a common type and branch with when: catch (e: Exception) { when (e) { is IOException, is NumberFormatException -> … else -> throw e } }. The else -> throw e passes every other exception on to the caller. When each type needs its own handling, write one catch block per type instead.
Exception handling in Kotlin looks like Java's, with a few differences that change how you write it: there is no | to catch two types in one block, try is an expression that returns a value, there are no checked exceptions (so no throws clause), and use replaces try-with-resources. The sections below cover catching several types in one block, separate catch blocks with finally, throwing your own exceptions (and what require, check and error throw), runCatching and Result, closing resources with use, and @Throws for Java callers, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1One catch block with when (e)Recommended
Java 7 lets you write catch (IOException | NumberFormatException e). Kotlin has no such syntax; here that line fails to compile with Syntax error: Expecting ')'. The Kotlin way is to catch a type that covers all of them, often Exception, and test the real type with when. A branch can list several types separated by commas, and the else branch rethrows what you didn't mean to handle, so a bug such as an IllegalStateException doesn't get swallowed by accident.
import java.io.IOException fun load(input: String): Int = when (input) { "disk" -> throw IOException("disk not ready") "closed" -> error("cache is closed") else -> input.toInt() } fun readCount(input: String): Int? = try { load(input) } catch (e: Exception) { // One catch, several types: test them with when when (e) { is NumberFormatException, is IOException -> { println("skipped $input: ${e::class.simpleName}") null } else -> throw e // anything else goes up to the caller } } fun main() { for (input in listOf("42", "abc", "disk")) { println("count = ${readCount(input)}") } try { readCount("closed") } catch (e: IllegalStateException) { println("caller got: ${e.message}") } }
Output
"abc" throws a NumberFormatException and "disk" an IOException; the same branch handles both and readCount returns null. "closed" throws an IllegalStateException, which the when doesn't list, so else -> throw e sends it up and main prints caller got: cache is closed. Because try is an expression, the whole function is one expression body.
2Separate catch blocks, try as an expression and finally
When each type needs its own handling, chain catch blocks. The first block whose type matches wins, so put the most specific types first: FileNotFoundException is a subclass of IOException and goes before it. try is an expression, so val text = try { … } catch … takes the value of whichever branch ran, which replaces the Java habit of declaring a variable before the try. finally runs on every path, success or exception, and its value is ignored.
import java.io.FileNotFoundException import java.io.IOException fun openConfig(name: String): String = when (name) { "missing" -> throw FileNotFoundException("$name.conf") "locked" -> throw IOException("$name.conf is locked") "empty" -> throw IllegalArgumentException("$name.conf has no port") else -> "port=8080" } fun describe(name: String): String { // try is an expression: it gives the value of the branch that ran val text = try { openConfig(name) } catch (e: FileNotFoundException) { // the most specific type goes first "not found: ${e.message}" } catch (e: IOException) { "I/O problem: ${e.message}" } catch (e: IllegalArgumentException) { "bad config: ${e.message}" } finally { // runs on every path; its value is ignored println("checked $name") } return text } fun main() { for (name in listOf("app", "missing", "locked", "empty")) { println(describe(name)) } }
Output
Each name takes a different path, and checked … prints every time, before the result: finally runs before describe returns. The missing file lands in the first block (not found: missing.conf), not in the IOException one. Swap those two blocks and the program still compiles here, but a FileNotFoundException then goes to the IOException block and the specific block never runs. If two blocks share the same handling, move it into a small function and call it from both, or use the when form from section 1.
3Throw custom exceptions, require, check and error
A custom exception is a class that extends Exception (or RuntimeException; in Kotlin the difference doesn't matter), and you throw it with throw, no new. Give your exceptions a common sealed base class and callers can catch the whole family with one block, then use a when that needs no else. Pass the original exception as the cause when you wrap one. For everyday checks you don't need a class at all: require, check and error throw standard exceptions with your message.
// A sealed base class groups your exceptions; catch the base once sealed class OrderException(message: String, cause: Throwable? = null) : Exception(message, cause) class OutOfStockException(val item: String) : OrderException("$item is out of stock") class PaymentException(val code: Int, cause: Throwable) : OrderException("payment declined ($code)", cause) fun placeOrder(item: String, card: String) { if (item == "lamp") throw OutOfStockException(item) val number = try { card.toInt() } catch (e: NumberFormatException) { throw PaymentException(402, e) // keep the original as the cause } println("ordered $item with card $number") } fun main() { val orders = listOf("desk" to "4242", "lamp" to "4242", "desk" to "VISA") for ((item, card) in orders) { try { placeOrder(item, card) } catch (e: OrderException) { // when over a sealed class needs no else branch val fix = when (e) { is OutOfStockException -> "restock ${e.item}" is PaymentException -> "cause: ${e.cause?.message}" } println("${e.message} -> $fix") } } // require, check and error throw standard exceptions for you val amount = -5 val shipped = true val checks = listOf<Pair<String, () -> Unit>>( "require" to { require(amount > 0) { "amount must be > 0: $amount" } }, "check" to { check(!shipped) { "order already shipped" } }, "error" to { error("unknown status") }, ) for ((name, action) in checks) { try { action() } catch (e: Exception) { println("$name: ${e::class.simpleName}: ${e.message}") } } }
Output
One catch (e: OrderException) handles both failures, and the when reads each one's own fields: restock lamp and the wrapped cause, For input string: "VISA". The last three lines show what the helpers throw: require gives IllegalArgumentException (for bad arguments), check and error give IllegalStateException (for a bad state). Without a message block, a failed require says Failed requirement. and a failed check says Check failed.
4runCatching and Result as a return type
runCatching { … } runs a block and returns a Result: Success with the value, or Failure with the exception. A function can return Result<Int> so the caller decides what a failure means, with getOrDefault, getOrNull, getOrElse, onFailure or fold. The old Stack Overflow error 'kotlin.Result' cannot be used as a return type is gone: Kotlin 1.5 lifted that restriction, and the function below compiles as is.
// Result<T> as a return type: success or the exception, no throw fun parsePort(text: String): Result<Int> = runCatching { val port = text.trim().toInt() require(port in 1..65535) { "port out of range: $port" } port } fun main() { for (text in listOf("8080", "http", "70000")) { println("$text -> ${parsePort(text)}") } // Read the value with a fallback println(parsePort("http").getOrDefault(80)) println(parsePort("443").getOrNull()) println(parsePort("http").getOrNull()) // Branch on the failure type, like a catch with when val port = parsePort("70000").getOrElse { e -> when (e) { is NumberFormatException -> 80 is IllegalArgumentException -> 65535 else -> throw e } } println("port = $port") // Side effects and fold parsePort("abc").onFailure { println("log: ${it.message}") } val text = parsePort("22").fold( onSuccess = { "ssh on $it" }, onFailure = { "no port" }, ) println(text) // Trap: runCatching catches everything, errors included println(runCatching { TODO("write this") }.exceptionOrNull()) }
Output
A printed Result shows its state: Success(8080), or Failure(…) with the exception inside. The getOrElse block gets the exception, so the when from section 1 works there too; the out-of-range port is an IllegalArgumentException and gives port = 65535. The last line is the trap: runCatching catches every Throwable, so even kotlin.NotImplementedError, an Error that a catch (e: Exception) would let through, ends up in the Result. In coroutine code it also catches the cancellation signal; use a plain try/catch there.
5use {}: Kotlin’s try-with-resources
Kotlin has no try (Resource r = …) syntax. Instead, every Closeable and AutoCloseable has a use function: reader.use { … } runs the block, closes the resource when the block ends, normally or by an exception, and returns the block's value. For several resources, nest the calls. File.useLines and readText open and close the file for you.
import java.io.File class Connection(private val name: String) : AutoCloseable { init { println("open $name") } fun query(sql: String): String { require(sql.isNotBlank()) { "empty query" } return "rows for $sql" } override fun close() = println("close $name") } fun main() { File("notes.txt").writeText("first line\nsecond line\n") // use closes the reader when the block ends, like try-with-resources val first = File("notes.txt").bufferedReader().use { it.readLine() } println(first) // close runs even when the block throws try { Connection("db").use { c -> println(c.query("")) } } catch (e: IllegalArgumentException) { println("caught: ${e.message}") } // Two resources: nest use; they close in reverse order Connection("source").use { source -> Connection("target").use { target -> println(source.query("users")) } } // useLines opens, reads lazily and closes the file for you println(File("notes.txt").useLines { lines -> lines.count() }) }
Output
The failed query shows the order: open db, then close db, and only then caught: empty query. use closed the connection before the exception reached the catch, just as Java's try-with-resources does. The nested pair opens source then target and closes them in reverse. If close() itself throws while an exception is already in flight, use attaches the second one to the first as a suppressed exception instead of losing it.
6No checked exceptions, and @Throws for Java callers
Kotlin has no checked exceptions: a function never declares throws IOException, and a caller is never forced to catch one. That is why a method signature with throws Exception has no direct Kotlin form. It matters when Java code calls your function: Java only lets you catch a checked exception that the method declares. @Throws(IOException::class) writes that declaration into the compiled class, so Java callers can (and must) catch it.
import java.io.IOException import kotlin.reflect.jvm.javaMethod // No throws clause: Kotlin has no checked exceptions fun readConfig(path: String): String = throw IOException("cannot read $path") // @Throws writes a throws clause into the bytecode for Java callers @Throws(IOException::class) fun readConfigForJava(path: String): String = throw IOException("cannot read $path") fun main() { // What Java sees on each function println(::readConfig.javaMethod?.exceptionTypes?.map { it.simpleName }) println(::readConfigForJava.javaMethod?.exceptionTypes?.map { it.simpleName }) // Kotlin never forces a try/catch, but you can still add one try { readConfig("app.conf") } catch (e: IOException) { println("caught: ${e.message}") } // A Java Runnable cannot throw IOException in Java; in Kotlin it can val task = Runnable { readConfigForJava("db.conf") } try { task.run() } catch (e: IOException) { println("from Runnable: ${e.message}") } }
Output
The first two lines read each function's Java signature: [] for the plain function and [IOException] for the annotated one. Both throw the same exception at run time; the annotation changes only what Java's compiler sees. The Runnable lambda shows the other side: in Java, () -> readConfig(…) would not compile as a Runnable without wrapping the checked exception, while Kotlin passes it through as is. Add @Throws only to functions that Java code calls.
7Which should you use?
| Method | Catches | Best for |
|---|---|---|
| catch (e: Exception) { when (e) … } | Listed types, rethrows the rest | Several types with the same handling (Java multi-catch) |
| catch (e: A) … catch (e: B) | First matching block | A different handling for each type |
| catch (e: SealedBase) | Your whole family | Your own exceptions, with an exhaustive when |
| runCatching { … } | Every Throwable | Returning Result, chaining fallbacks |
| x.use { … } | Nothing, closes x | Files, readers, connections (try-with-resources) |
| catch (e: Throwable) | Errors too | Top-level logging only; rethrow or exit after |
Frequently asked questions
Does Kotlin have multi-catch like Java's catch (A | B e)?
No. catch (e: IOException | NumberFormatException) is a syntax error in Kotlin. Catch a common supertype, often Exception, and branch with when (e) { is IOException, is NumberFormatException -> … else -> throw e }, or write one catch block per type and move the shared code into a function.
What is the Kotlin equivalent of try-with-resources?
The use extension function on Closeable and AutoCloseable: File("a.txt").bufferedReader().use { it.readLine() } reads a line and closes the reader whether the block finishes or throws. Nest use calls for several resources; they close in reverse order.
How do I declare that a Kotlin function throws an exception?
You don't need to: Kotlin has no checked exceptions, so there is no throws clause and callers are never forced to catch. Mention it in the KDoc with @throws. If Java code calls the function and should be able to catch a checked exception, add the annotation @Throws(IOException::class), which writes the throws clause into the bytecode.
Can kotlin.Result be used as a return type?
Yes. Older Kotlin versions rejected it with 'kotlin.Result' cannot be used as a return type, and Kotlin 1.5 lifted that restriction. fun parsePort(text: String): Result<Int> = runCatching { text.toInt() } compiles, and the caller reads it with getOrNull(), getOrDefault(), getOrElse { } or fold().
How do I throw a custom exception in Kotlin?
Declare a class that extends Exception, such as class OutOfStockException(val item: String) : Exception("$item is out of stock"), and throw it with throw OutOfStockException("lamp"); there is no new. Pass a cause to the Exception constructor when you wrap another exception, so the original stays in the stack trace.
What is the difference between require, check and error in Kotlin?
require(condition) { "message" } throws IllegalArgumentException and is for checking arguments. check(condition) { "message" } throws IllegalStateException and is for checking an object's state. error("message") always throws IllegalStateException. requireNotNull and checkNotNull do the same for null values and return the value non-null.
Is try an expression in Kotlin?
Yes. val n = try { text.toInt() } catch (e: NumberFormatException) { 0 } gives the value of the try block, or of the catch block that ran. The finally block runs either way, but its value is ignored. For this exact case text.toIntOrNull() ?: 0 is shorter.
Run it yourself
Open any of these in the full Kotlin editor to tweak, run and share.
Kotlin playground