0
0
KotlinHow-ToBeginner · 3 min read

How to Throw Exception in Kotlin: Syntax and Examples

In Kotlin, you throw an exception using the throw keyword followed by an exception object, like throw IllegalArgumentException("message"). This immediately stops the current function and passes the exception up the call stack.
📐

Syntax

To throw an exception in Kotlin, use the throw keyword followed by an instance of an exception class. The syntax looks like this:

  • throw ExceptionType("error message"): Throws a new exception of the specified type with a message.

The throw keyword is an expression, so it can be used anywhere an expression is allowed.

kotlin
throw IllegalArgumentException("Invalid argument")
💻

Example

This example shows how to throw and catch an exception in Kotlin. The function checkAge throws an IllegalArgumentException if the age is less than 18.

kotlin
fun checkAge(age: Int) {
    if (age < 18) {
        throw IllegalArgumentException("Age must be at least 18")
    }
    println("Age is valid: $age")
}

fun main() {
    try {
        checkAge(15)
    } catch (e: IllegalArgumentException) {
        println("Caught exception: ${e.message}")
    }
}
Output
Caught exception: Age must be at least 18
⚠️

Common Pitfalls

Some common mistakes when throwing exceptions in Kotlin include:

  • Forgetting to create an exception object and just writing throw ExceptionType without parentheses.
  • Throwing exceptions without meaningful messages, which makes debugging harder.
  • Not catching exceptions where needed, causing the program to crash unexpectedly.

Always create an exception instance with a clear message and handle exceptions properly.

kotlin
fun wrongThrow() {
    // Wrong: missing parentheses
    // throw IllegalArgumentException()

    // Right:
    throw IllegalArgumentException("This is the correct way")
}
📊

Quick Reference

ActionSyntax Example
Throw exceptionthrow IllegalStateException("Error message")
Catch exceptiontry { /* code */ } catch (e: Exception) { /* handle */ }
Create custom exceptionclass MyException(message: String) : Exception(message)

Key Takeaways

Use the throw keyword followed by an exception object to throw exceptions in Kotlin.
Always provide a clear message when throwing exceptions to help with debugging.
Remember to catch exceptions where appropriate to prevent program crashes.
The throw keyword is an expression and can be used anywhere an expression is allowed.
Common mistake: forgetting parentheses when creating an exception instance.