Skip to content
Tutorials Center
My learning

Topics

Lesson 80 of 134 ยท Error Handling and Resources

Resources and use

Learn how Kotlin's use function closes resources safely - Closeable and AutoCloseable, close order, suppressed exceptions, return values, files and readers - with runnable examples.

Some objects hold on to something that is not memory the garbage collector can simply reclaim: an open file, a network socket, a database connection, a lock, a native buffer. The operating system gives only so many file handles to a process, a database allows only so many connections, and a half-written file may not be flushed to disk until you close it. Such objects must be closed explicitly when you are done, and they must be closed even when the code in between fails.

On the JVM the contract is the interface AutoCloseable (and its older sub-interface java.io.Closeable): a single method, close(). Kotlin adds the function use, which is Java's try-with-resources as an ordinary library function. After this lesson you will know how to write it, what it guarantees, the subtle case of two exceptions at once, and how to make your own classes work with it.

The problem: cleanup that is easy to forget

Here is a resource and a naive way to use it. The class prints when it is opened and closed, so we can see what happens:

Kotlin Forgetting to close (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 second send throws, so session.close() is never reached. The output ends with the uncaught IllegalArgumentException: cannot send an empty message, and close A is never printed. The resource leaks. In a long-running server that leak repeats on every failed request until the process runs out of handles.

The classic fix is try/finally:

Kotlin
// read-only example: the manual way
val session = Session("A")
try {
    session.send("hello")
    session.send("")
} finally {
    session.close()
}

It works, but it is verbose, it makes you declare the variable outside the try, and it gets worse with two resources (you need nested try/finally blocks, and the exception handling of close() itself is easy to get wrong). use removes that ceremony.

use: the safe way

use is an extension function on Closeable and on AutoCloseable. It runs your lambda with the resource as the argument and closes the resource afterwards, whether the lambda finished normally or threw.

Kotlin use closes the resource in every case

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 session B, the order of the lines is open B, B sends 'hi', then close B, then caught: cannot send an empty message. The resource is closed while the exception is travelling outward, before the catch block runs, which is exactly what you want: by the time you handle the problem, the cleanup is done. The exception itself is not swallowed; it continues to the caller after close() returns.

Key properties of use:

  • It is inline, so it adds no lambda object, and you can return, break or continue from inside the lambda as in a normal block (it will still close the resource).
  • It returns the value of the lambda, so you can compute a result and leave the resource in one expression.
  • The resource is only visible inside the lambda, which stops you from using it after it was closed.
Kotlin use returns the lambda's value

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.

Several resources and the closing order

Each use closes its own resource. Nest them for several resources; they close in the reverse order of opening, like a stack, which is correct because a later resource often depends on an earlier one (a reader on top of a stream, a statement on top of a connection).

Kotlin Nested use closes in reverse order

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 opens connection, statement, result set, prints the work line, then closes result set, statement, connection.

There is no special syntax for several resources in one use (Java 9+ lets you list them in the try (...) header). With Kotlin you nest the calls, or write a small helper. If the nesting gets deep, extract inner blocks into functions.

When close() fails too: suppressed exceptions

What if the lambda throws and then close() also throws? Two exceptions exist, but only one can propagate. use keeps the first one (the real problem in your code) and attaches the one from close() to it as a suppressed exception. You can read them with e.suppressed (a Array<Throwable>) or e.suppressedExceptions.

Kotlin A failure in the block and in close

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 first block reports IllegalArgumentException: work failed as the main exception and the close failure as suppressed. In the second block the work succeeds but close() throws, so the close failure is the exception you see.

This is better than the hand-written finally { resource.close() }, where an exception from close() would replace the original one and hide the real cause. If you ever write that pattern yourself, you are likely to lose the first exception.

Making your own class closable

Implement AutoCloseable (or Closeable if it does IO) and put the cleanup in close(). Good close() methods are idempotent: calling them twice must be harmless, because some code paths close a resource twice.

Kotlin An idempotent close

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 pool.close() after use printed nothing the second time, and that a closed pool refuses further work through check (see require, check and assert).

Files and readers

Most standard IO classes are Closeable: FileReader, BufferedWriter, InputStream, Socket, and the JDBC Connection. Kotlin's file helpers readText(), writeText(), forEachLine() and useLines {} open and close the file for you, so prefer them when they fit. The files themselves are the topic of Files and IO. The sandbox can create temporary files during a run:

Kotlin Writing and reading a temporary file

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.

useLines hands you a lazy Sequence<String> and closes the file when the lambda returns, so you must finish consuming the sequence inside the lambda. Returning the sequence itself would give the caller a sequence over a closed file.

Pitfalls

  • Using the resource after use. The object still exists, but it is closed. Keep the lambda's result a plain value (a list, a string), not the resource or a lazy view over it.
  • Forgetting that use does not catch. It closes the resource and rethrows. If you also need to handle the exception, wrap the use call in try/catch.
  • A resource created inside use's own receiver expression that throws. In Session("A").use { }, if the constructor throws, there is nothing to close, and use is never called. That is correct, but it means a constructor that opens two things must clean up the first itself if the second fails.
  • Coroutines and use. use is fine inside suspend functions, but closing is a blocking call and runs on whichever thread resumed the coroutine; for slow IO use a suitable dispatcher (see Dispatchers and Context).
  • Java's try (a; b) has no direct twin. The nested use approach is idiomatic.

AutoCloseable.use and Closeable.use are two separate extension functions, because Closeable appeared first. They behave the same. On a null receiver, use works too if the type is nullable (Closeable?.use), and simply skips the close.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does use call close()?

    use is Kotlin's try-with-resources: it always closes the resource, then lets any exception continue.
  2. 2. Three nested use blocks open A, then B, then C. In which order are they closed?

    Each use closes its own resource as its lambda ends, and the innermost lambda ends first, so closing happens in reverse order of opening.
  3. 3. The lambda in use throws, then close() throws a second exception. What does the caller see?

    The first exception is the one that propagates; the exception from close() is added to its suppressed list so no information is lost.
  4. 4. What does file.useLines { it } get wrong?

    useLines closes the file when the lambda returns. A lazy sequence returned from it would read from a closed file, so consume it (toList, count, ...) inside the lambda.
  5. 5. Which interface must a class implement to be used with use?

    use is defined as an extension on AutoCloseable and Closeable. Implement close() and make it safe to call more than once.

Summary

  • Resources such as files, sockets and connections must be closed even when code fails; on the JVM they implement AutoCloseable or Closeable.
  • resource.use { ... } runs the lambda, then always calls close(), even on early return or an exception, and returns the lambda's result.
  • Nested use blocks close in reverse order of opening.
  • If both the block and close() throw, the block's exception propagates and the close() exception is attached as suppressed.
  • Make your own classes AutoCloseable with an idempotent close(); use useLines, readText and similar helpers for files.
  • Do not let the resource, or a lazy view of it, escape the use block.

Next: Custom Exceptions and Error Design