Kotlin Throw Exception Using the throw Keyword

Kotlin uses the throw keyword to raise an exception explicitly. A function can throw a standard exception such as IllegalArgumentException or an application-specific exception class. The exception then moves up the call stack until a matching catch block handles it; if it remains unhandled, the current operation terminates.

Unlike Java, Kotlin treats all exceptions as unchecked. A Kotlin function therefore does not have to declare thrown exceptions in its signature. See the official Kotlin exceptions documentation for the language rules.

Kotlin throw Exception Syntax

To throw an exception to the calling code, use the throw keyword followed by an exception object.

The simplified syntax to throw an exception is:

</>
Copy
throw Exception(message : String)

The message passed to the exception describes the failure. Calling code can read it through the exception’s message property. In working Kotlin code, the expression normally appears as throw Exception("message").

Example 1 – Throw an Exception in Kotlin

Consider an application that requires an account to maintain a minimum balance of 1000. The following program calls a validation function inside a try block and prints the exception message from the corresponding catch block.

example.kt

</>
Copy
package exception_handling

fun main(args: Array<String>) {

    var amount = 600

    try {
        validateMinAmount(amount)
    } catch (e : Exception){
        println(e.message)
    }

}

fun validateMinAmount(amount : Int){
    throw Exception("Your balance $amount is less than minimum balance 1000.")
}

In this example, validateMinAmount() throws the exception whenever it is called. The catch block receives that exception and prints its message.

Output

Your balance 600 is less than minimum balance 1000.

Throw an Exception Only When Kotlin Validation Fails

A validation function should usually throw only when its condition is not satisfied. If the value is valid, the function can return normally.

</>
Copy
fun validateMinAmount(amount: Int) {
    if (amount < 1000) {
        throw IllegalArgumentException(
            "Your balance $amount is less than minimum balance 1000."
        )
    }
}

fun main() {
    try {
        validateMinAmount(600)
        println("Balance accepted")
    } catch (e: IllegalArgumentException) {
        println(e.message)
    }
}

IllegalArgumentException is suitable here because the function received an argument outside its accepted range. Catching this specific exception is clearer than catching the general Exception type.

Throw a Custom Exception in Kotlin

A custom exception gives a domain-specific name to a failure. This can help calling code distinguish a minimum-balance failure from unrelated exceptions. Define the custom class by extending Exception or a more specific exception superclass.

Create a Kotlin file called CustomExceptions.kt.

CustomExceptions.kt

</>
Copy
class MinimumBalanceException(message: String) : Exception(message)

In the same location as the file above, create another Kotlin file named example.kt.

example.kt

</>
Copy
fun main(args: Array<String>) {

    var amount = 600

    try {
        validateMinAmount(amount)
    } catch (e : MinimumBalanceException){
        println(e.message)
    } catch (e : Exception){

    }

}

fun validateMinAmount(amount : Int){
    throw MinimumBalanceException("Your balance $amount is less than minimum balance 1000.")
}

The first catch handles MinimumBalanceException specifically. When several catch clauses are present, place specific exception types before broader types such as Exception. An empty general catch block can hide unexpected failures, so production code should handle, log, or rethrow such exceptions as appropriate.

Output

Your balance 600 is less than minimum balance 1000.

Use throw as a Kotlin Expression

In Kotlin, throw is an expression. This allows it to appear on the right side of the Elvis operator. The thrown expression has the type Nothing, which represents a computation that does not complete normally.

</>
Copy
fun requireUsername(username: String?): String {
    return username ?: throw IllegalArgumentException("Username is required")
}

fun main() {
    println(requireUsername("Meera"))
}

If username is not null, the function returns it. If it is null, evaluation switches to the right side of ?: and throws the exception.

Kotlin throw, require, check, and error

Kotlin provides standard helper functions for common failure conditions:

  • require(condition) throws IllegalArgumentException when a function argument is invalid.
  • check(condition) throws IllegalStateException when an object’s current state is invalid.
  • error(message) always throws IllegalStateException and has the return type Nothing.
  • An explicit throw is appropriate when another exception type or custom exception is required.
</>
Copy
fun withdraw(balance: Int, amount: Int): Int {
    require(amount > 0) { "Withdrawal amount must be positive" }
    check(balance >= amount) { "Insufficient balance" }
    return balance - amount
}

Catch Multiple Exception Types in Kotlin

Kotlin does not use Java’s multi-catch syntax with a vertical bar. Add separate catch clauses when failures need different handling. Order them from the most specific exception type to the most general type.

</>
Copy
try {
    val quantity = "ten".toInt()
    println(100 / quantity)
} catch (e: NumberFormatException) {
    println("Quantity must be an integer")
} catch (e: ArithmeticException) {
    println("Quantity cannot be zero")
}

Declare Kotlin Exceptions for Java Callers with @Throws

Kotlin itself does not require a throws clause. When a Kotlin function is called from Java, the @Throws annotation can add the specified exception types to the generated JVM method declaration. This is mainly useful for Java interoperability.

</>
Copy
import java.io.IOException

@Throws(IOException::class)
fun loadConfiguration() {
    throw IOException("Configuration file could not be read")
}

The annotation does not make the exception checked inside Kotlin. It only affects how the function is exposed to callers on platforms such as the JVM.

Kotlin Exception-Throwing QA Checklist

  • Confirm that the exception is thrown only when the documented validation condition fails.
  • Choose a specific standard exception or a clearly named custom exception instead of using Exception for every failure.
  • Place specific catch clauses before broader catch clauses.
  • Do not leave catch blocks empty or silently discard unexpected exceptions.
  • Test both the exception path and the successful path of the Kotlin function.
  • Add @Throws only when Java or another platform caller needs declared exception metadata.

Kotlin Throw Exception FAQs

Does Kotlin have checked exceptions?

No. Kotlin does not distinguish checked exceptions from unchecked exceptions at the language level. A function can throw an exception without declaring it, and callers are not required by the compiler to catch it.

How do I throw an exception from a Kotlin function?

Create an exception object after the throw keyword, for example, throw IllegalArgumentException("Invalid amount"). The function stops at that point unless surrounding code catches the exception.

How do I create a custom exception in Kotlin?

Declare a class that extends Exception or another suitable exception class, such as class MinimumBalanceException(message: String) : Exception(message). Throw it in the same way as a built-in exception.

Can a Kotlin throw expression return a value?

A throw expression does not return normally. Its type is Nothing, which lets it be used in expressions such as value ?: throw Exception("Missing value").

When should Kotlin code use @Throws?

Use @Throws when generated method declarations need to expose exception types to Java or other platform callers. It is not required for ordinary Kotlin-to-Kotlin calls.

Kotlin Throw Exception Summary

In this Kotlin Tutorial, we learned how to throw standard and custom exceptions, catch specific exception types, use throw as an expression, apply Kotlin validation helpers, and expose declared exceptions to Java callers with @Throws.