Ruang penulis
← Kembali ke jurnal
Kotlin

How do I throw an exception when a value is null using ?: throw in Kotlin?

Use Kotlin’s Elvis operator ?: with throw on the right-hand side: val value: String? = getNullableValue() val nonNullValue: String = value ?: throw IllegalArgumentException("value must not be null") Because throw is an expression in Kotlin, it can be used after ?:. Example fun printLength(text: String?) { val nonNullText = text ?: throw IllegalArgumentException("text must not […]

DWayan · 26 Jun 2026 · 1 menit baca

Artikel oleh Wayan · Sumber: Kode Java ↗

Terjemahan artikel ini belum tersedia. Isi asli ditampilkan.

Use Kotlin’s Elvis operator ?: with throw on the right-hand side:

val value: String? = getNullableValue()

val nonNullValue: String = value ?: throw IllegalArgumentException("value must not be null")

Because throw is an expression in Kotlin, it can be used after ?:.

Example

fun printLength(text: String?) {
    val nonNullText = text ?: throw IllegalArgumentException("text must not be null")

    println(nonNullText.length)
}

If text is not null, it is assigned to nonNullText as a non-nullable String.
If text is null, the exception is thrown.

You can also use other exception types:

val id = nullableId ?: throw IllegalStateException("ID was unexpectedly null")

A common choice is:

  • IllegalArgumentException when a function argument is invalid
  • IllegalStateException when the object/program state is invalid
← Jelajahi catatan lainnya