CodeGym /Courses /Kotlin SELF /Multiple catch blocks

Multiple catch blocks

Kotlin SELF
Level 12, Lesson 5
Available

1. How catch is selected and why order matters

When you first master try/catch, you really want to do this: “OK, I’ll catch everything and print one message.” It feels like armor, like a magic shield from all troubles. The problem is that it’s a cardboard shield: yes, it will stop crashing, but you’ll stop understanding what’s happening, and the user will just get “error” with no hints about what exactly they did wrong.

In Kotlin, a catch handler runs only if an exception actually occurred inside try, and Kotlin selects the first matching catch from top to bottom. And “matching” means not only an exact type match, but also a match by hierarchy: if you catch a more general exception class, it will “cover” more specific ones too. This is crucial for today’s topic: the order of catch blocks determines the program’s behavior.

To feel the benefit of multiple catch blocks, imagine a simple console program where the user enters a number. The errors can be different: they might enter "12a" (format issue), they might enter 0 (division by zero), or they might enter index 100 for an array of three elements (bounds issue). If you report all of that with one phrase, you get a sad quest: “guess what’s wrong.”

The “first matching” rule

Now there will be a bit of “formal math,” but without it it’s easy to write code that looks correct… and doesn’t work the way you think.

Handler selection can be represented like this:

flowchart TD
    A[Code in try] --> B{Did an exception occur?}
    B -->|no| C[Skip catch, move on]
    B -->|yes| D[Compare with 1st catch]
    D --> E{Does the type match?}
    E -->|yes| F[Run this catch]
    E -->|no| G[Try the next catch]
    G --> E

The key point: the check goes top to bottom, and only the first matching handler will run.

Why is this related to the hierarchy? Because exceptions have “parents”: for example, NumberFormatException is a specific kind of error, and Exception is a very general “parent” for many runtime errors. If you put a handler for the “parent” too early, it will take control, and more specific handlers won’t get a chance.

Specific first, general last

A very typical beginner path looks like this: “let’s make the first catch catch Exception, just to be safe…”. Kotlin usually responds quite strictly: “buddy, there’s a catch for NumberFormatException below, but it will never run, because Exception will catch everything earlier.” And that’s good: the compiler literally saves you from broken logic.

Let’s look at an example of an incorrect order. It’s short but illustrative:

fun main() {
    try {
        println(readln().toInt())
    } catch (e: Exception) {
        println("Any error")
    }
    catch (e: NumberFormatException) { ... } // not allowed: unreachable
}

This code demonstrates the principle: a general catch (e: Exception) should be the “last line of defense,” if you decide to write it at all.

And here is a variant where the order is already reasonable: first catch the specific cause, and then a maximally general option in case something unexpected happens.

fun main() {
    try {
        println(readln().toInt())
    } catch (e: NumberFormatException) {
        println("Error: you must enter an integer") // e.g., "12a"
    } catch (e: Exception) {
        println("Unexpected error: ${e.message}")
    }
}

Note that e.message can be null, and that’s fine (not all exceptions must have text). But even with null, you at least understand: “something went off-plan, and it’s not a format error.”

By the way, if you’re a Java programmer: Kotlin does not require catching exceptions explicitly (in Kotlin they are “unchecked”), but it allows you to do so if you want to turn a crash into controlled behavior.

2. Granularity: how precisely to catch exceptions

Granularity is a word that sounds like a brand of expensive coffee, but it means a simple thing: how specifically you distinguish the causes of errors.

You can catch very specifically: NumberFormatException separately, ArithmeticException separately, ArrayIndexOutOfBoundsException separately. Then you can give the user the most accurate hint possible. But if you write 30 lines in each catch, the program turns into a three-volume novel, “Sufferings of Handlers.” And yes, novels can be interesting, but the compiler doesn’t read them.

You can catch too broadly: one catch (e: Exception) and print “Error.” Then the program doesn’t crash, but you lose diagnostics and the ability to explain to the user what exactly is wrong. At that point the app starts to resemble an ATM that prints “ERROR” and stares at you disapprovingly.

A healthy middle is usually this: expected, understandable errors are handled specifically; unexpected ones are either not caught at all (let it crash and show a stack trace, especially in learning programs), or caught as the last catch (e: Exception) with a neutral message, without pretending that we “fixed everything.”

A small reference table:

Approach What we write What we get in the end
Too general catch (e: Exception) and one text “Doesn’t crash,” but it’s unclear why
Too fine-grained 10 different catch blocks + complex logic Accurate, but bulky and hard to maintain
Practical 2–4 specific ones + a general one at the end Clear for the user, and the logic reads well

Handling strategy: expected vs. unexpected errors

Now we’ll bring it all into one idea: multiple catch blocks are not “because it looks nicer,” but because different causes require different actions.

If the user entered "12a" instead of a number, it’s an expected input error. The program should calmly explain that digits are required and, possibly, ask to retry input (you already know how to do that using loops). It’s not a catastrophe; it’s just the human factor: people have fingers.

If the user entered a divisor of 0, that’s also an expected situation. Yes, you can’t divide by zero, but it’s easy to explain.

If you suddenly got an ArrayIndexOutOfBoundsException, the situation is two-sided. Sometimes it’s also an “expected” error (if the user enters the index themselves). But sometimes it’s a pure bug in the program: you miscomputed the index. And here an overly general catch can mask the real error, causing you to spend hours searching for why “sometimes the program behaves strangely.”

So strategically it’s useful to ask yourself a simple question: who is at fault?

If the user is at fault (input), print a friendly message and stay alive. If the code is at fault (a bug), it’s better for the developer to see it. In learning programs it can even be more useful not to catch such an exception at all, so you get a stack trace and quickly find the line where you made a mistake.

3. Practical example: a mini “Grades” program

Let’s continue practicing in the style of “console mini-apps” that we’ve been building since day one: input, simple logic, output. Suppose we have an array of grades, and the user wants to view a grade by index and compute “10 / d” (so we deliberately have a chance to catch division by zero). Yes, it’s an artificial example, but it honestly trains several different exceptions.

First, let’s make a small data skeleton:

fun main() {
    val grades = intArrayOf(5, 4, 3)

    print("Grade index: ")
    val rawIndex = readln()

    print("Divisor: ")
    val rawDiv = readln()

    // we'll add try/catch next
}

Now let’s add try and multiple catch blocks. Note: inside try we have three places where things can go wrong at once: toInt() (format), grades[i] (bounds), 10 / d (division by zero). That means it makes sense to distinguish the causes.

fun main() {
    val grades = intArrayOf(5, 4, 3)

    try {
        val i = readln().toInt()
        val d = readln().toInt()

        println("Grade = ${grades[i]}")
        println("10 / d = ${10 / d}")
    } catch (e: NumberFormatException) {
        println("Error: input must be an integer")
    } catch (e: ArrayIndexOutOfBoundsException) {
        println("Error: index is out of range 0..${grades.lastIndex}")
    } catch (e: ArithmeticException) {
        println("Error: division by zero")
    }
}

Two things matter here.

First: we catch three different exceptions and print three different messages. That’s the practical value of multiple catch blocks.

Second: the order. There is no Exception here, but the “specific first” idea still holds. And if we added a general handler, it should be last, otherwise it would “eat” the others.

4. Minimize try: split handling into blocks

Now we’ll do a small refactor in thinking, not “architecture of the century.” A common recommendation: try should be as small as possible—cover only what can actually fail and what you truly want to handle.

In the previous example we covered a lot at once. That’s fine for learning “multiple catch blocks.” But in real life it can sometimes be more useful to separate index input from computations. Then you understand more precisely which operation failed, and the code becomes easier to test by eye.

For example, you can do it like this: one try for parsing numbers, and a second one for working with the array and division. We don’t have to do it this way, but as a thinking tool it helps.

fun main() {
    val grades = intArrayOf(5, 4, 3)

    val i = try { readln().toInt() }
    catch (e: NumberFormatException) { return }

    val d = try { readln().toInt() }
    catch (e: NumberFormatException) { return }

    try {
        println(grades[i])
        println(10 / d)
    } catch (e: Exception) {
        println("Computation error: ${e.message}")
    }
}

Here I intentionally used return in case of invalid input. It’s not “perfect UX,” but it’s a neat demonstration: if the input is invalid, there’s nothing further to do, because we don’t have valid numbers. You already know that return allows you to end a function quickly.

And yes, there is a general catch (e: Exception) in the second block. This is sometimes acceptable as a “last line of defense,” but it should be used consciously and kept simple.

5. Messages in catch and a general handler

What to tell the user

When you already know how to catch different exceptions, a new danger appears: you start writing “real application logic” inside catch, as if it were a normal if branch. You can do that, but it quickly hurts readability: the main scenario becomes jagged because the logic spreads across handlers.

In a console learning program, it’s usually enough for catch to do three things: briefly explain the problem, hint at the correct input, and return the program to a controlled state (for example, exit or ask for input again).

For example: if you catch NumberFormatException, it’s useful to say “you need an integer”—and not dump a wall of “java.lang.NumberFormatException: For input string: ...” to the user. That message is pleasant only for someone who wanted to see a stack trace (that is, you when debugging), not for the user.

A general catch as insurance, not a trash bag

A general catch (e: Exception) is like a big “miscellaneous” bag in a closet. It’s sometimes needed, but if you put everything there, you stop understanding where anything is.

If you add a general catch, keep two rules in mind.

First, it must be last; otherwise, more specific handlers become unreachable because the general handler catches exceptions earlier.

Second, it must not pretend that it “fixed everything.” If you catch absolutely everything, your message should be honest and neutral: “unexpected error”—and possibly e.message. You don’t have to “heal” what you don’t understand.

Here is a typical template for a learning console program:

fun main() {
    try {
        println("Result: ${100 / readln().toInt()}")
    } catch (e: NumberFormatException) {
        println("Error: you need an integer")
    } catch (e: ArithmeticException) {
        println("Error: division by zero")
    } catch (e: Exception) {
        println("Unexpected error: ${e.message}")
    }
}

Here the first two catch blocks are “expected” errors for this scenario, and the last one is insurance.

6. Common mistakes when working with multiple catch blocks

Mistake #1: putting catch (e: Exception) first.
It looks like “I’ll make it universal,” but conceptually it breaks the whole idea of multiple handlers. A more general type catches more specific cases, and in the end your neat catch (e: NumberFormatException) either becomes unreachable (the compiler will complain) or you simply never see it in action. The correct habit is to arrange catch blocks from the most specific to the most general.

Mistake #2: printing the same text in all catch blocks.
If in every handler you print “Error,” you technically wrote multiple catch blocks, but they provide zero practical value. The point of branching is that reactions should differ: “not a number” and “division by zero” are different hints to the user, and they should be separated at least by text.

Mistake #3: turning catch into a “second main” with complex logic.
In handlers, a beginner sometimes starts writing half the program: re-entering data, recreating arrays, starting loops, and printing 40-line reports. That makes the code hard to read: the main scenario falls apart into pieces. It’s better for catch to be short, and for complex logic to live in normal functions and the normal execution flow.

Mistake #4: catching an exception “just in case” and silently swallowing it.
An empty catch is like taping over the “Check Engine” light: the car doesn’t stop breaking; you just stop learning about it. Even in a learning program, the minimum is to print a clear message. Otherwise you lose diagnostics and then wonder why “sometimes it does nothing.”

Mistake #5: confusing “where it happened” and “where it was handled.”
An exception is thrown on a specific line inside try, and handled in catch. If you don’t keep that connection in mind, you get odd expectations like “I’ll write catch and the program will continue from the same line.” No: the line where the exception occurred does not “finish”; execution jumps to catch. Therefore, after try/catch it makes sense to keep code such that it works correctly both in the successful scenario and in the error-handling scenario.

Mistake #6: an overly broad try that hides the source of the problem.
When try covers “half the program,” you lose track of which operation can fail and which error you are actually handling. This is especially unpleasant if there are many different actions inside try: input, computations, working with arrays. Try to make try wrap a small fragment that you can explain in words: “here I parse a number” or “here I access an array element.”

1
Task
Kotlin SELF, level 12, lesson 5
Locked
Square of Failures
Square of Failures
1
Task
Kotlin SELF, level 12, lesson 5
Locked
Splitting the pizza
Splitting the pizza
1
Task
Kotlin SELF, level 12, lesson 5
Locked
Chest by Index
Chest by Index
1
Task
Kotlin SELF, level 12, lesson 5
Locked
Two validation stages
Two validation stages
1
Survey/quiz
Exception handling, level 12, lesson 5
Unavailable
Exception handling
Exception handling
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION