CodeBlanks Logo Icon CodeBlanks

try/catch

Learn to catch errors with try/catch.

try/catch: catching errors

A piece of code may throw an error; a try block wraps that code, catch catches the error. The program then continues without crashing.

try {
    val x = 10 / 0
} catch (e: ArithmeticException) {
    println("Error: ${e.message}")
}

If the code inside try fails, control jumps to catch. The caught object is bound to e; e.message carries the error text. Catching the right exception type prevents unexpected failures.

Specific exception types

Each error type points to a different situation. The most common: ArithmeticException, NumberFormatException, NullPointerException, IndexOutOfBoundsException.

try {
    val n = "abc".toInt()
} catch (e: NumberFormatException) {
    println("Not a number")
}

The right type matters for handling the error well. For unknown errors you can catch Exception; but specific types give clearer information. A wrong type lets the error slip past.

Practice Wrap division in try/catch

Inside a try block write val x = 10 / 0. Catch ArithmeticException and print "Error" with println.

Starter code

Main.kt
fun main() {
    // Wrap a division in try; catch the error and print Error
}

Sample solution

Main.kt
fun main() {
    try {
        val x = 10 / 0
    } catch (e: ArithmeticException) {
        println("Error")
    }
}

Expected output

Hata

Questions and answers

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

1 What does the catch block do?

  • It throws an error
  • It must ignore the error
  • It repeats the error
  • It catches the error Correct answer

Explanation: catch catches the error raised inside try.

2 Fill in the blank: write catch

Question
try {
    val x = 10 / 0
} ____ (e: ArithmeticException) {
    println("Error")
}
Answer
try {
    val x = 10 / 0
} catch (e: ArithmeticException) {
    println("Error")
}

Explanation: catch catches the ArithmeticException.

3 Match exception to scenario

Term Meaning
ArithmeticException Division error
NumberFormatException Conversion error
IndexOutOfBoundsException Array bound
NullPointerException Null access

All lessons in Beginner