Skip to content
Tutorials Center
My learning

Topics

Lesson 79 of 134 ยท Error Handling and Resources

require, check and assert

Learn Kotlin preconditions - require, check, requireNotNull, checkNotNull, error and assert - when to use each, which exception they throw, and how they enable smart casts. Runnable examples.

A function is a small contract. It expects certain things from its caller (a positive amount, a non-empty list) and it expects certain things of itself (the account is open, the list is sorted at this point). When a contract is broken, the best moment to find out is immediately, with a clear message pointing at the cause, not ten calls later when a negative number has already spread through your data.

Kotlin's standard library has a small family of functions for this: require, check, requireNotNull, checkNotNull, error and assert. They are short, they read like English, and the compiler understands them well enough to smart-cast values afterwards. This lesson explains which one to use for which kind of mistake, what each throws, and how to write good failure messages.

require: checking arguments

require(condition) says "the caller must have passed something valid." If the condition is false it throws IllegalArgumentException. Put these checks at the top of a function, before any work is done.

Kotlin require rejects bad arguments (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 first call prints 12. The second ends the program: Exception in thread "main" java.lang.IllegalArgumentException: whole must be positive, was 0, followed by a stack trace and a non-zero exit code. The lambda after require(...) is the message supplier. It is only evaluated when the check fails, so building the message costs nothing in the normal case. Without a lambda the message is the generic Failed requirement., which tells the reader nothing, so always supply a message that names the offending value.

check: checking state

check(condition) says "this object (or this program) must be in a valid state to do this." A false condition throws IllegalStateException. The difference from require is who is to blame: with require the caller passed the wrong thing; with check the state is wrong, however it got that way.

Kotlin check guards the state of an object

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.

Nothing is wrong with the arguments here (there are none); the call is simply not allowed at this moment. Typical check uses: "the connection must be open", "you must call start() before stop()", "an iterator must not be advanced past the end", and invariants in the middle of an algorithm.

A quick way to choose:

Question Use Throws
Is a parameter acceptable? require IllegalArgumentException
Is the object or program in the right state? check IllegalStateException
Should this point be impossible? error("...") IllegalStateException

Callers can catch these separately because they are different types, though in practice you let them propagate: they signal bugs, not situations to recover from. Do not catch IllegalArgumentException just to continue as though nothing happened; fix the caller. (For expected bad input such as text typed by a user, prefer toIntOrNull() or a result; see The Result Type.)

The generic messages

When you omit the lambda, each function uses a fixed default message. These are the real strings:

Kotlin Default messages and exception types

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.

Read the output closely. require and requireNotNull throw IllegalArgumentException with Failed requirement. and Required value was null.; check and checkNotNull throw IllegalStateException with Check failed. and Required value was null. TODO throws kotlin.NotImplementedError, which is an Error, not an Exception (so a plain catch (e: Exception) would not catch it, and the demo above catches Throwable). Custom messages replace the defaults.

requireNotNull and checkNotNull: checks that smart-cast

The ...NotNull versions return the non-null value, so they work as both a check and a conversion:

Kotlin requireNotNull returns the 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.

This is the clean replacement for !!: it states why the value must not be null and gives a message. Use requireNotNull for values that came in (arguments and their properties), and checkNotNull for values that are part of the object's own state, such as a field that must have been initialized earlier.

require and check also help the compiler directly. Their definitions carry a contract that says "if this call returns, the condition was true", so Kotlin smart-casts afterwards:

Kotlin Smart casts after require and check

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.

You can see how contracts work in Smart Casts and Contracts.

error: this should never happen

error(message) always throws IllegalStateException and has the return type Nothing, so it fits anywhere. It is perfect for a branch the programmer believes unreachable:

Kotlin error in an impossible branch (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 last line stops the program with IllegalStateException: unknown level 'urgent', expected one of [LOW, MEDIUM, HIGH]. Because error returns Nothing, it works on the right of ?: and the whole expression has type Level. There is a deeper treatment of Nothing in Any, Unit and Nothing.

assert: checks for development only

assert(condition) is the odd one out. On the JVM it throws AssertionError only when assertions are enabled with the -ea flag (java -ea), and they are disabled by default. In production, with the flag off, assert does nothing. Gradle's test task usually enables assertions; the Android runtime does not.

That makes assert a tool for "this should always be true, and I would like to know during development and tests, but I do not want to pay for it in production or crash a customer's app." It is unsuitable for validating anything that must always be checked, such as input.

The runner here does not pass -ea, so assertions are off:

Kotlin assert is silent by default

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.

Both false assertions are ignored, so you see survived a false assertion. Two lessons hide here. First, the assert(Boolean) overload is an inline function, but its argument is still evaluated (expensiveCheck() ran once) even when assertions are off, so keep assertion conditions cheap or free of side effects. Only the lambda form assert(condition) { "message" } skips building the message. Second, the code did not crash, so never put real validation in an assert.

For demonstration purposes you can switch assertions on at run time, before the first assertion executes; real programs just start the JVM with -ea.

Kotlin Turning assertions on (demonstration only)

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.

With assertions enabled the failed assertion throws java.lang.AssertionError: arithmetic is broken. Note that AssertionError is an Error, like NotImplementedError: ordinary catch (e: Exception) blocks do not see it.

Choosing, in practice

  1. Validating public inputs (arguments, configuration, data from outside): require, or requireNotNull.
  2. Guarding an object's lifecycle or an internal invariant that must hold in production: check, checkNotNull.
  3. A branch that cannot happen (or a value that must exist): error(...).
  4. Something you want verified in tests and development only: assert.
  5. Code you have not written yet: TODO(), which compiles anywhere (its type is Nothing) and fails loudly when reached.
  6. Failures that callers are expected to handle: not these functions. Return a nullable, a sealed result or a Result.

Two style notes. Write messages for the person who will read the stack trace at 2 a.m.: say what was expected and what was received ("port must be in 1..65535, was $port"). And keep the checks close to the start of a function so a violated precondition fails before side effects happen.

require and check are ordinary inline functions. A failed require throws a normal exception, so you can test it with assertFailsWith<IllegalArgumentException> in your tests (see Testing in Kotlin). Document the preconditions in KDoc with @throws IllegalArgumentException.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A caller passes a negative quantity to addItem(quantity: Int). Which check fits best?

    A bad argument is the caller's mistake, so require (IllegalArgumentException) is right. assert is off by default, so it would not protect production.
  2. 2. Which exception does a failed check(...) throw?

    check signals a wrong state and throws IllegalStateException with the message 'Check failed.' unless you provide your own.
  3. 3. What is special about requireNotNull(x) { ... } compared with require(x != null)?

    requireNotNull returns x with a non-null type (and throws IllegalArgumentException when it is null), so val v = requireNotNull(x) works as check and conversion in one.
  4. 4. Why should real validation never rely on assert?

    Without -ea the assert condition has no effect. Use require or check for checks that must always run.
  5. 5. What is the return type of error("message")?

    error never returns normally, so its type is Nothing. That lets you write value ?: error("missing") where a value of any type is expected.

Summary

  • require checks arguments and throws IllegalArgumentException; check checks state and throws IllegalStateException; error throws IllegalStateException and has type Nothing.
  • requireNotNull and checkNotNull return the non-null value, a tidy alternative to !!; require and check also enable smart casts through contracts.
  • The message lambda is evaluated only on failure; always write one that names the bad value.
  • assert throws AssertionError only when the JVM runs with -ea; it is off by default, so use it for development checks, never for validation.
  • TODO() throws NotImplementedError, an Error rather than an Exception.
  • Preconditions signal bugs. For failures callers should handle, return a nullable, a sealed type or a Result.

Next: Resources and use