CodeGym /Courses /Kotlin SELF /Exceptions in logs

Exceptions in logs

Kotlin SELF
Level 60, Lesson 2
Available

1. Introduction

When a program breaks, a beginner really wants to do this: catch the exception, print e.message, and calm down. It’s like a situation where your car lights up “Check Engine”, and you put a piece of tape over it that says “everything is fine”. Yes, the light no longer annoys you, but the car is still in an unclear condition—and most importantly, you lost the information that could let you fix the problem quickly.

With exceptions in logs, the task is exactly the same: preserve as much diagnostic value as possible, but not turn the application into a “chatty parrot” that prints a 20-page novel for every little thing. In this lecture we’ll find the balance: we’ll add a stack trace, learn how to correctly “wrap” exceptions while preserving the cause, and choose the right places to log so we don’t duplicate the same thing at every level.

What exactly do we log: Throwable, Exception, Error

Before printing a stack trace, it’s important to understand that in Kotlin (and on the JVM) exceptions are objects, and they have a hierarchy. The root of this hierarchy is Throwable, which Exception and Error inherit from. Exception is what you can usually (and sometimes should) handle, while Error is “the universe broke” (roughly speaking), like OutOfMemoryError, where your application can rarely continue in a sensible way.

The practical takeaway for our logging is simple: when we design a logger API like error(..., e: Throwable), we are not limited to Exception. We are ready to accept whatever actually arrived. But in a catch it’s usually reasonable to catch Exception (or specific types), because catching Error and continuing “as if nothing happened” is sometimes worse than honestly crashing.

A small illustration (not a “rule for all cases”, but a useful guideline):

fun main() {
    try {
        val x = "not a number".toInt()
        println(x)
    } catch (e: Exception) {
        println("Failed to read a number") // user-facing
    }
}

Here we catch Exception because this is a typical conversion error. But if the JVM starts running out of memory—pretending everything is fine is usually pointless.

2. Stack trace: what it is and why it matters

A stack trace is the runtime’s report of which functions were called until the program reached the point where the exception occurred. In plain human terms: it’s the “route” by which the error came to visit us. On the JVM, the stack trace is usually printed automatically if the exception is unhandled.

The key point: a stack trace answers the question “WHERE exactly did it crash?”. The exception message (e.message) more often answers “WHY did it roughly crash?”, and even that is not always clear. So the rule for logs is: if we log an ERROR-level error, then in most cases we want to see the stack trace—otherwise debugging turns into guesswork.

A mini-example of “what a crash with a stack trace looks like” (we won’t copy the full output, but you’ve already seen the idea earlier in the exceptions topic):

fun boom() {
    error("Boom!")
}

fun main() {
    boom()
}

If you don’t catch it, the JVM will print the exception type, the location, and the call chain.

4. stackTraceToString(): a convenient way to put a stack trace into a log

You can also mess up printing a stack trace “any old way”. For example, trying to manually iterate over e.stackTrace and concatenate lines is a great exercise in patience, but usually not required.

On the JVM in Kotlin, there is a convenient method Throwable.stackTraceToString(), which returns the stack trace as a single string. This is convenient for our console logger: we can print one log line with the message and context, and then as the next chunk print the stack trace as a separate block. It reads well and is easy to copy.

Let’s make a small helper example: catch an exception, convert the stack trace to a string, print it.

fun main() {
    try {
        "12x".toInt()
    } catch (e: Exception) {
        println(e.stackTraceToString()) // stack trace will be here
    }
}

Yes, this is not a “logger” yet, but you can already see that the stack trace can be obtained in a controlled way, not only “automatically on crash”.

5. Extending Logger: message + context + exception

Now let’s assemble everything into our familiar construct: Logger is the single place where formatting and output are decided. We already know how to print the timestamp, level, message, and context. Now we’ll add a Throwable? parameter and agree on the format: first the main log line, then (if there is an exception) print its stack trace as a separate block.

An important idea: the calling code should not have to think “how do I pretty-print the exception”. It should just pass a Throwable, and the logger will do the rest.

Example (a snippet; assume you already have formatCtx(...) from the previous lecture about context):

class Logger(private val minLevel: LogLevel) {

    private fun enabled(level: LogLevel): Boolean =
        level.ordinal >= minLevel.ordinal

    fun error(message: String, ctx: Map<String, String> = emptyMap(), e: Throwable? = null) {
        if (!enabled(LogLevel.ERROR)) return
        val ts = System.currentTimeMillis()
        println("$ts [ERROR] $message" + formatCtx(ctx))
        if (e != null) println(e.stackTraceToString())
    }
}

Notice: we accept Throwable?, not only Exception. And we print the stack trace only when e != null. This matters because sometimes ERROR is a “scenario failure without an exception”, for example “failed to save the file because there are no permissions” (you might have handled it and returned an error as a value). But if there is an exception—we don’t lose it.

6. Cause (cause): how not to lose the root source of the problem

A very common mistake is to “wrap” an exception but lose the original cause. It looks like this: somewhere deep down it failed with a useful exception (for example, NumberFormatException), and at the top you threw a new IllegalStateException("Something went wrong") without linking it to the original. As a result, the stack trace shows the top layer, the true cause disappears, and then you spend hours looking for who exactly “did something wrong”.

Correct wrapping on the JVM: create a new exception and pass the original as the cause.

A mini-example of “how it should be”: catch, add context, rethrow with the cause.

fun parsePort(raw: String): Int {
    try {
        return raw.toInt()
    } catch (e: Exception) {
        throw IllegalArgumentException("Port must be a number: raw='$raw'", e)
    }
}

The point of this code is not to “catch everything”, but to add clear context at this level. If someone above logs this exception, the stack trace will show both our layer (with the message about the port) and the original cause (for example, NumberFormatException), which actually explains what happened.

7. Responsibility boundaries: where to log the exception

The most unpleasant kind of logs is when the same exception is printed 5 times in a row because it’s logged “just in case” at every level: in the parsing function, in the command handler, in main, in the storage logger, and somewhere else in a utility nobody remembers. Logs bloat, important messages get lost, and you read it like “War and Peace”, only without Pierre Bezukhov or meaning.

So we need the concept of a responsibility boundary. A simple working model for a console app:

  • Internal functions either handle the error and return control “in a normal form”, or throw the exception upward (possibly wrapping it with a cause).
  • Exception logging is done at the point where we have the operation context and where we make the decision: “the scenario ended with an error”.

If you have a command-line app, that boundary is often the command handler: it knows the command, input parameters, maybe a requestId, and it decides what to show the user.

Schematically, it can look like this:

flowchart TD
    A[main reads a line] --> B[dispatcher: determine the command]
    B --> C[command handler]
    C --> D[internal functions: parsing/validation/storage]
    D -->|throw| C
    C -->|log ERROR + ctx + stacktrace| E[Logger]
    C -->|user-facing message| F[println for the user]

Point C is often an ideal place for logging: there is already enough information, but we haven’t risen too high and lost the scenario details.

8. Practice: a command handler as the logging point

Let’s take a typical piece of a command-line application: the user enters a command, we try to parse an argument (for example, an amount), and then do something. Assume our project already has Logger and context.

We’ll make a handler that catches the exception exactly once, logs it, and shows the user a short message.

fun handleAdd(amountRaw: String, logger: Logger) {
    val ctx = mapOf("command" to "add", "amountRaw" to amountRaw)

    try {
        val amount = amountRaw.toInt()
        println("Added an expense: $amount") // example user output
    } catch (e: Exception) {
        logger.error("Failed to process command add", ctx = ctx, e = e)
        println("Error: the amount must be an integer") // user-facing
    }
}

There are several important “grown-up” decisions here, even though the code is short.

We log the technical error with context and stack trace so the developer (or you a week later) can understand where it failed. And separately we write a friendly user message without unnecessary details. The user usually doesn’t need a NumberFormatException; they need to understand “what to do differently”.

9. Useful nuances of exception logging

Don’t log too deep: little context, lots of noise

Sometimes it seems logical: “I caught the exception where it happened, so I should log it there.” But deep inside an application there is often no operation context. For example, parseAmount(raw) only knows the string—it doesn’t know the command, it doesn’t know the requestId, it doesn’t know the scenario. As a result, the logs become faceless: “Parse failed”, “Parse failed”, “Parse failed”—and that’s it.

In that situation, it’s better to do one of two things:

Option one: rethrow the exception upward without logging, but if needed, wrap it by adding meaning and preserving the cause. That way we get a useful message, but the log will still be a single one at the top.

Option two: return an error as a value (if you already have such an architecture), but that requires discipline. Today we stay closer to try/catch and exceptions, because the point of this lecture is specifically exception logging.

An example of “don’t log deep—add meaning and rethrow”:

fun parseAmount(raw: String): Int {
    try {
        return raw.toInt()
    } catch (e: Exception) {
        throw IllegalArgumentException("Invalid amount: raw='$raw'", e)
    }
}

And we will log at the top, where there is command and other fields.

How to read a stack trace: what is useful in it first

A stack trace can look scary, especially early on: lots of lines, unfamiliar classes, sometimes JVM internals. But the good news is: for 80% of cases you only need two things.

First, the top line with the exception type and message.

Second, the first few at ... lines until you see your file and your line. As a rule, the most valuable place is the first frame in your code where it actually failed (for example, Main.kt:42), not where the logger prints.

To help yourself, you can agree on a style: we print the main log line (timestamp/level/message/ctx), and the stack trace as a separate block right after. Then visually it’s clear: “here is the event”, “here are the exception details”.

Don’t silently “swallow” exceptions

In exception logging there is another typical issue: “caught it—did nothing—moved on”. Externally, the program keeps working, but in reality it can drift into a strange state: data is partially updated, state is inconsistent, the user got “success” even though a failure actually occurred.

So the rule is simple: if you caught an exception, then you either handled the situation correctly (for example, asked the user to enter the data again), or at least you logged it and ended the scenario in a clear way. “Eating an exception” without a log is almost always “borrowing problems from your future self”.

An example of bad code:

fun risky() {
    try {
        "x".toInt()
    } catch (e: Exception) {
        // silence...
    }
}

Even if you don’t want to crash, the minimum is to log at the right responsibility boundary.

10. Common mistakes

Mistake #1: logging only e.message and thinking that’s “diagnostics”.
An exception message is often too short and doesn’t answer the main question: “where did it crash?”. The stack trace is created precisely to show the call chain and the crash point. If there is no stack trace in an ERROR log, then in a real investigation you will almost certainly spend more time than you could have.

Mistake #2: wrapping an exception and losing the cause (cause).
When you throw a new exception “with a clearer text” but don’t pass the original as the cause, you destroy the most valuable part of diagnostics: the root cause and the original stack trace. The correct technique is to pass the original exception as the second constructor argument so the cause is preserved and ends up in the stack trace.

Mistake #3: logging the same exception at every call level.
If the parser, the command handler, and main all print an ERROR with a stack trace for the same error, the logs turn into duplicates. That’s not “more information”, it’s “more noise”. You need one consistent logging point—usually the operation boundary where you have maximum context.

Mistake #4: catching too broad a type and continuing as if nothing happened.
Catching Throwable in a catch and pretending everything is ok is dangerous, because you might catch Error-level situations where continued execution is not guaranteed. For most scenarios it’s enough to catch Exception or specific exceptions, and the logger should be able to accept any Throwable if you want to log what actually arrived.

Mistake #5: showing the user a stack trace instead of a normal message.
A stack trace is useful to a developer, but almost useless to a user and often scary. A good style is: for the user, short and clear—“invalid input”, “failed to open file”, “please try again”. And in the log—everything technical: ERROR level, context, stack trace. That way you take care of both UX and diagnostics.

1
Task
Kotlin SELF, level 60, lesson 2
Locked
Crash diagnostics
Crash diagnostics
1
Task
Kotlin SELF, level 60, lesson 2
Locked
Error with an exception
Error with an exception
1
Task
Kotlin SELF, level 60, lesson 2
Locked
Port without loss
Port without loss
1
Task
Kotlin SELF, level 60, lesson 2
Locked
Single log entry
Single log entry
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION