1. What Is an Exception?

[THEORY]

[PREDICT]

Read the code carefully before you run it.

prediction.kt
fun registerOrder(quantity: Int, stock: Int) {
    if (quantity > stock) {
        throw IllegalStateException("Not enough stock: $quantity requested, $stock available")
    }
    println("Order ($quantity units) registered successfully")
}

fun main() {
    println("Start")
    registerOrder(15, 10)
    println("End")
}

What does the program output? Is "Ende" still printed?

[TASK]

Write a function registerOrder(quantity: Int, stock: Int). If quantity is greater than stock, throw an IllegalStateException with the message "Not enough stock: $quantity requested, $stock available". Otherwise print "Order ($quantity units) registered successfully". Call the function in main() with quantity = 15 and stock = 10 — the program should abort with a stack trace. Catching is the topic of the next lesson; here it is only about throw.

task.kt
fun registerOrder(quantity: Int, stock: Int) { // TODO: throw an IllegalStateException when there is not enough stock // TODO: otherwise print the success message } fun main() { registerOrder(15, 10) }

Before you get a hint: what have you tried, and where exactly are you stuck?

[COMPREHENSION CHECK]

1. According to common convention, what should you NOT use exceptions for?

2. Throwable is the base class of the Kotlin exception hierarchy. Which two direct subclasses does it have?