CodeBlanks Logo Icon CodeBlanks

Custom exceptions

Learn to write custom exception classes in Kotlin.

Custom exceptions: your own error class

You can define your own class for application-specific errors. It inherits from a generic exception type; you pass the message to the constructor.

class TaskError(message: String) : Exception(message)

throw TaskError("Task not found")

The class name explains the error clearly. You can also choose RuntimeException instead of Exception. A custom type makes both catching and debugging easier.

Throwing and catching custom exceptions

You throw your class with throw and catch it with catch. The type name shows which error is caught.

try {
    throw TaskError("Not found")
} catch (e: TaskError) {
    println(e.message)
}

catch (e: TaskError) only catches this type. You can set up different catch blocks for different error types. This keeps error handling tidy and meaningful.

Practice Define the TaskError class

Define the class TaskError(message: String) : Exception(message). Write fun find(id: Int) that throws TaskError("Task not found: $id"). In main call find(99); catch TaskError and print e.message.

Starter code

Main.kt
fun main() {
    // Define an error class, throw it in a function, catch in main and print
}

Sample solution

Main.kt
class TaskError(message: String) : Exception(message)

fun find(id: Int) {
    throw TaskError("Task not found: $id")
}

fun main() {
    try {
        find(99)
    } catch (e: TaskError) {
        println(e.message)
    }
}

Expected output

Görev bulunamadı: 99

Questions and answers

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

1 Fill in the blank: superclass

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

Explanation: Exception is used as the superclass.

2 Why define a custom exception?

  • For less memory
  • To write less code
  • For speed
  • For more meaningful error types Correct answer

Explanation: Application-specific error types are more meaningful.

3 Match part to role

Term Meaning
class TaskError Class definition
: Exception Superclass
throw TaskError Throwing
catch (e: TaskError) Catching

All lessons in Beginner