CodeBlanks Logo Icon CodeBlanks

Error handling

Add error handling with try/catch.

Custom error: TaskNotFound

In this project we define a custom exception called TaskNotFound for invalid indexes. The error type then states the cause clearly.

class TaskNotFound(message: String) : Exception(message)

throw TaskNotFound("Task not found: 5")

The class inherits from Exception and passes the message via the constructor. When caught, e.message gives meaningful content. A custom type makes both catching and debugging easier.

The complete method and try/catch

The complete(index) method completes the task at the given index. If the index is past the list, it throws TaskNotFound; the caller catches it with try/catch.

fun complete(index: Int) {
    if (index >= tasks.size)
        throw TaskNotFound("Task not found: $index")
    tasks[index].done = true
}

try {
    list.complete(5)
} catch (e: TaskNotFound) {
    println(e.message)
}

The bound check happens before the throw. tasks.size gives the list length; an index equal to or beyond it is out of bounds. catch (e: TaskNotFound) catches only this type.

Practice Add the complete method and try/catch

Add fun complete(index: Int) to the TaskList class: if the index is greater than or equal to tasks.size, throw TaskNotFound("Task not found: $index"); otherwise set tasks[index].done = true. In main add a task, call list.complete(5); catch TaskNotFound with try/catch and print e.message.

Starter code

Main.kt
class Task(val title: String) {
    var done: Boolean = false
    override fun toString(): String {
        return if (done) "[x] $title" else "[ ] $title"
    }
}

class TaskNotFound(message: String) : Exception(message)

class TaskList {
    val tasks = mutableListOf<Task>()
    fun addTask(title: String) {
        tasks.add(Task(title))
    }
    fun listDone() = tasks.filter { it.done }
    // complete metodunu yaz: sınır dışı indekste TaskNotFound fırlat
}

fun main() {
    val list = TaskList()
    // Add a task; call complete(5); catch the error and print the message
}

Sample solution

Main.kt
class Task(val title: String) {
    var done: Boolean = false
    override fun toString(): String {
        return if (done) "[x] $title" else "[ ] $title"
    }
}

class TaskNotFound(message: String) : Exception(message)

class TaskList {
    val tasks = mutableListOf<Task>()
    fun addTask(title: String) {
        tasks.add(Task(title))
    }
    fun listDone() = tasks.filter { it.done }
    fun complete(index: Int) {
        if (index >= tasks.size) throw TaskNotFound("Task not found: $index")
        tasks[index].done = true
    }
}

fun main() {
    val list = TaskList()
    list.addTask("Study Kotlin")
    try {
        list.complete(5)
    } catch (e: TaskNotFound) {
        println(e.message)
    }
}

Expected output

Görev yok: 5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: declare TaskNotFound

Question
class TaskNotFound(message: String) : ____(message)
Answer
class TaskNotFound(message: String) : Exception(message)

Explanation: Exception is used as the superclass.

2 Why define a custom exception?

  • Less code
  • For more meaningful error types Correct answer
  • Less memory
  • Speed

Explanation: Application-specific error types are more meaningful.

3 Match piece to role

Term Meaning
class TaskNotFound Error class
: Exception Superclass
throw TaskNotFound Throwing
catch (e: TaskNotFound) Catching

All lessons in Beginner