Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 134 ยท Control Flow

Exceptions

Learn Kotlin exceptions - try/catch/finally as expressions, throw, the exception hierarchy, custom exceptions, no checked exceptions, runCatching and use, with runnable examples and real error output.

Things go wrong. A file is missing, a user types "abc" where a number is expected, a list is empty when you ask for its first element, a network call times out. An exception is Kotlin's way of reporting such a failure: the code that detects the problem throws an exception object, normal execution stops, and the runtime looks outward through the calling functions for code that is prepared to catch it. If nobody catches it, the program ends and prints a stack trace.

Kotlin runs on the JVM, so its exceptions are the same Throwable classes Java uses, and everything you learn here applies to Java libraries too. There are, however, a few Kotlin differences that make exception handling lighter: try is an expression, there are no checked exceptions, and the standard library has helpers such as runCatching, require and use.

What an uncaught exception looks like

Start by seeing what happens when you do nothing. The program below divides by zero:

Kotlin An uncaught exception (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is start and 5, then the program stops with Exception in thread "main" java.lang.ArithmeticException: / by zero, followed by lines starting with at: the stack trace, which lists the functions that were active when the exception was thrown, innermost first, with file and line numbers. end is never printed. Learn to read the first line (the exception class and message) and then the first at MainKt... line, which points at your code.

try and catch

To handle the exception, wrap the risky code in try and add one or more catch blocks. The type in the parentheses decides which exceptions the block handles.

Kotlin Catching exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

When the code in try throws, execution jumps to the first catch whose type matches (the exception's class or any of its superclasses). The lines after the throwing statement inside try are skipped. After the catch block finishes, the program continues after the whole try statement, and it is back to normal.

Every exception has a message (a String?), an optional cause (the exception that triggered this one) and a stack trace. Printing e itself shows the class name and the message; e.message shows only the message.

You can list several catch blocks. They are checked from top to bottom, so put the most specific type first:

Kotlin Several catch blocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The last block catches any Exception and acts as a safety net. Note that catching Exception too broadly can hide bugs, so catch the narrowest type that you can actually do something about. And don't catch Throwable unless you really mean it: it also includes Error subclasses such as OutOfMemoryError and StackOverflowError, which signal that the JVM itself is in trouble.

try is an expression

In Kotlin try returns a value: the last expression of the try block, or of the catch block that ran. That removes a lot of temporary vars:

Kotlin try as an expression

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

For this particular job there is an even simpler tool, "abc".toIntOrNull() ?: default. Prefer the ...OrNull functions when failure is expected, as with user input, and keep exceptions for situations that are truly exceptional. An exception is much slower than a normal return (building a stack trace costs time), and it makes the code's flow harder to follow.

finally: cleanup that always runs

A finally block runs whether the try block succeeded, threw an exception that was caught, or threw one that was not. It is the place for cleanup that must happen.

Kotlin finally always runs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice the order: even when the function executes return, finally runs first. The value of a try expression comes from try or catch, never from finally; a finally that contains its own return would override the result and swallow exceptions, so do not do that.

Several catch blocks and nested try

A try can have more than one catch. Kotlin checks them from top to bottom and runs the first one whose type matches, so put the most specific exception first and the general ones last. A broad type such as Exception placed first would catch everything and make the later blocks unreachable in practice.

Kotlin Ordering catch blocks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

NumberFormatException and ArithmeticException are both subclasses of Exception, so the last block is a safety net for anything unexpected. Kotlin has no catch (A | B e) multi-catch syntax; if two exceptions need the same handling, catch their common supertype or call a shared function from both blocks.

A try can also sit inside another try, or inside a catch or finally. The inner one handles what it can; anything it does not catch travels outward to the next enclosing try. You can also rethrow: catch an exception, do something (log it, add context), and throw again, usually wrapping the original as the cause.

Kotlin Nested try, finally and rethrowing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output shows the order: opening, then closing (the finally runs before the exception leaves loadConfig), and the outer catch reports both the new message and the original cause. Two warnings. If a finally block itself throws or returns, it replaces whatever was in flight, so keep finally free of risky code. And do not nest try blocks just to be careful: usually one try with an ordered list of catch blocks is clearer, and a small helper function per step is clearer still.

Throwing exceptions

You throw with throw, followed by an exception object. In Kotlin throw is an expression of type Nothing, so it can appear anywhere a value is expected, for instance on the right of ?::

Kotlin Throwing your own exceptions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The last statement ends the program with the NullPointerException and its message. Choose the exception type that tells the caller what kind of mistake happened:

Exception Use it for
IllegalArgumentException A caller passed a bad argument
IllegalStateException The object is in the wrong state for this call
UnsupportedOperationException An operation is not supported
NoSuchElementException A requested element does not exist
IndexOutOfBoundsException An index is outside the valid range
ArithmeticException Math error, such as integer division by zero

Because checking arguments and state is so common, Kotlin has shortcuts: require(amount > 0) { "..." } throws IllegalArgumentException, check(...) throws IllegalStateException, and error("message") throws IllegalStateException directly. You will meet them in require, check and assert.

Custom exceptions

When the built-in types are too general, define your own by extending Exception (or a more specific class). Keep them small, and give them the data a handler needs.

Kotlin A custom exception with data and a cause

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Wrapping a low-level exception in a higher-level one and passing the original as cause keeps the full story available to whoever logs it. A larger design for exception hierarchies is discussed in Custom Exceptions and Error Design.

No checked exceptions

In Java, some exceptions are checked: a method must declare them with throws, and callers must catch them or declare them in turn. Kotlin has no checked exceptions. Nothing forces you to catch an IOException, and no signature lists what a function might throw. The designers' reasoning is that checked exceptions led to empty catch blocks and clutter in large code bases. The price is that you must read the documentation and think about which failures matter. If you want a function's failures to be visible in its type, return a result type instead: a sealed class, or Kotlin's built-in Result (see The Result Type).

runCatching: exceptions as values

runCatching { ... } runs the block and wraps the outcome in a Result: either the value (success) or the exception (failure). You then ask for what you need.

Kotlin runCatching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

runCatching is neat for turning "try this, otherwise use that" into a single expression, and for chains of operations. Two cautions. First, it catches every Throwable, including StackOverflowError, and in coroutine code it also catches CancellationException, which can break cancellation (see Cancellation and Timeouts). Second, a failure that you silently turn into a default value can hide a real bug; log it, or handle only the exception types you expect with an ordinary try.

use: closing resources safely

Files, sockets and database connections must be closed, even when something goes wrong. Types that need closing implement AutoCloseable (or Closeable), and Kotlin's use function closes them for you, like Java's try-with-resources:

Kotlin use closes the resource, even on failure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In the second case, close db2 is printed before caught: empty query: use closes the resource as the exception passes through. If both the block and close() throw, the first exception is kept and the second is attached to it as a suppressed exception. Resources and use covers this in depth.

Habits that keep exception code healthy

  • Catch only what you can handle. A catch (e: Exception) { } with an empty body makes bugs invisible. At the very least, log the exception.
  • Do not use exceptions for ordinary control flow. If a failure is a normal outcome (a missing key, bad user input), prefer getOrNull, toIntOrNull, or a result type.
  • Keep try blocks small. The smaller the block, the more clearly you know which call caused the exception.
  • Preserve the cause. When wrapping, pass the original exception as cause.
  • Print the stack trace when you debug. e.printStackTrace() or println(e.stackTraceToString()) shows where it happened; production code should use a logger.
  • Fail fast. Validate arguments at the top of a function so the error appears near its cause.

An uncaught exception in the main thread ends the program with a non-zero exit code, which your tools (CI, shell scripts) can see. A caught exception that you swallow ends with exit code 0 and hides the failure. Decide on purpose which one you want.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does println(x) print after val x = try { "7a".toInt() } catch (e: NumberFormatException) { -1 }?

    toInt() throws NumberFormatException for "7a", the catch block runs and, as the last expression, supplies the value -1.
  2. 2. When does a finally block run?

    finally is for cleanup and runs in all cases: success, caught exception, uncaught exception and early return.
  3. 3. Which statement about checked exceptions in Kotlin is true?

    Kotlin treats all exceptions as unchecked. Java's IOException, for example, can be ignored without declarations.
  4. 4. What is the type of throw IllegalStateException("x") as an expression?

    throw never completes normally, so its type is Nothing. That is why value ?: throw ... compiles for any type.
  5. 5. What does runCatching { ... } return?

    runCatching wraps the outcome in a Result<T>. Use getOrNull, getOrDefault, getOrThrow, recover or fold to deal with it.

Summary

  • An exception stops normal execution and travels up the call stack until a matching catch handles it; otherwise the program ends with a stack trace.
  • try, catch and finally work as in Java, but try is an expression that yields a value.
  • throw has type Nothing; use fitting types such as IllegalArgumentException and IllegalStateException, or define your own classes with extra data and a cause.
  • Kotlin has no checked exceptions; make failures visible with ...OrNull functions or result types when you want callers to handle them.
  • runCatching turns an exception into a Result value; use closes AutoCloseable resources reliably.
  • Catch narrowly, keep try blocks small, preserve causes and never swallow exceptions silently.

Next: Any, Unit and Nothing