Skip to content
Tutorials Center
My learning

Topics

Lesson 82 of 134 ยท Error Handling and Resources

Debugging and Printing

Learn practical Kotlin debugging - println tricks, a reusable dbg helper, readable toString, reading stack traces, stderr vs stdout, and when to switch to a real debugger or logger.

Every program you write will, at some point, do something you did not expect. Finding out why is a skill, and it is mostly the same few moves: look at the values, look at the path the code took, shrink the problem. Kotlin gives you good tools for the first two. You can print in a way that is quick and readable, you can make your own classes print usefully, and you can read the stack trace that every uncaught exception hands you for free.

This lesson covers the print-based techniques that work everywhere (including the in-browser runner on this site), how to read a stack trace line by line, and a short guide to where real debuggers and loggers take over. The goal is not to avoid bugs forever but to localize them in minutes instead of hours.

println debugging, done well

println is not shameful. It is the fastest feedback loop there is, and it works in any environment. The craft is in making the output self-explanatory, so that you can read it next week.

Always label values. A bare println(total) tells you a number, but not which one or where. Put the name in the string:

Kotlin Labelled printing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The '$name' quotes are a small habit with a big payoff: they show leading and trailing spaces, empty strings and strings that look like numbers. Lists print as [a, b, c] and maps as {k=v}, so you rarely need more.

Print at decision points. Instead of sprinkling prints everywhere, print where the code branches: at the start of a function (what came in), before a return (what goes out), and inside if/when branches (which path was taken).

A tiny dbg helper

Printing a value in the middle of an expression normally forces you to split the expression into several lines. The scope function also (see Scope Functions) lets you peek and carry on, and wrapping it in a generic extension makes it a one-word tool:

Kotlin A dbg extension to peek at values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Each .dbg("...") prints the value flowing through the chain and returns it unchanged, so the pipeline's meaning does not change. Remove the calls (your IDE can search for .dbg() when you are done. For sequences, which are lazy, the same trick works with onEach { println(it) } (see Sequences).

A close cousin is the Kotlin also itself: val user = loadUser(id).also { println("loaded $it") }. Use also for one-offs and dbg when you are going to peek many times.

Make your own classes print well

When you print an object of your own class, Kotlin calls toString(). The default implementation inherited from Any produces the class name and a hash, which is useless for debugging.

Kotlin Default toString versus a useful one

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first line prints true: the default is Point@ followed by a hash such as 1b2c3d, which changes from run to run, so never test or log against it. A data class, on the other hand, gets a readable toString automatically (Tagged(name=note, tags=[urgent, home])). For ordinary classes write a short toString that shows the fields you would want to see in a log. More about this in Object Basics: toString, equals, hashCode and Data Classes.

Two cautions. Do not call methods in toString that can throw or change state; it will be called by debuggers and loggers at any time. And do not include secrets (passwords, tokens) in it: toString output ends up in logs.

Printing structures

Nested structures print on one long line. A few helpers make them easier to read:

Kotlin Making structures readable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The array line is a classic trap. Arrays on the JVM do not override toString, so println(array) prints something like [I@5a07e868 (a type code and a hash). Always use contentToString() for arrays, or contentDeepToString() for arrays of arrays.

stdout, stderr and exit codes

A program has two output streams. println writes to standard output (stdout). Diagnostics belong on standard error (stderr), which a shell can redirect separately: program > result.txt keeps debug messages out of the file. In Kotlin you reach stderr through System.err:

Kotlin Two streams

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In this runner both streams appear in the output panel, in the order they were produced (the real order of interleaving on a terminal can differ, because the streams are buffered separately). In a real project, send diagnostics to stderr, or better, to a logger.

Reading a stack trace

When a program ends with an uncaught exception, the JVM prints a stack trace. It lists the chain of function calls that was active when the exception was created, innermost first. Treat it as a map: one line says what went wrong, the rest say how you got there.

Kotlin Read this stack trace (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program stops with Exception in thread "main" java.lang.NullPointerException, followed by these lines:

TEXT
	at MainKt.priceWithTax(main.kt:4)
	at MainKt.total(main.kt:11)
	at MainKt.main(main.kt:18)
	at MainKt.main(main.kt)

Read it from the top:

  1. The first line is the exception class and message: a NullPointerException, produced by !! on the null price.
  2. The first at line names the function and line where it was thrown: priceWithTax, line 4 of main.kt. That is where to look first.
  3. The lines below show who called it: total at line 11 (inside the loop), called by main at line 18. The last line is the generated entry point that calls your main().

So the story is: main called total, which called priceWithTax with the item whose price was null, and !! threw. The cause of the bug, a null price in the cart, is in the data, which the stack trace points to indirectly (second line: which call, which item). Often the line that throws is the symptom and one of the lines below is the real culprit.

With a cause chain (an exception wrapped in another, see Custom Exceptions and Error Design) the trace has several sections; the Caused by: section at the bottom is usually the root problem.

You can get the same information without crashing:

Kotlin Stack traces on demand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

e.stackTraceToString() returns the trace as a string, which you can log, truncate or attach to an error report. e.printStackTrace() writes it to stderr. Throwable().stackTrace is the trick for "who called this?" without throwing anything. Frames are StackTraceElement objects with className, methodName, fileName and lineNumber.

Checks that explain themselves

Instead of printing and eyeballing, let the program check its own assumptions: require, check and error stop with a message exactly where an assumption breaks (see require, check and assert). An assertion at the start of a function often finds a bug sooner than any amount of printing:

Kotlin Failing early with a message (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first call prints avg = 6.0; the second stops with IllegalArgumentException: average() needs at least one value, naming the function and the rule. Without the require, the answer would be NaN (0.0 / 0), which silently spreads through later calculations.

A debugging routine that works

  1. Reproduce it. Find the smallest input that triggers the problem and write it down (or make it a test).
  2. Read the error. Exception class, message, first at line in your code. Resist guessing before you have read all of it.
  3. State what you expected and what happened, in one sentence each. The gap is the bug.
  4. Bisect. Print the value halfway through the computation. Is it already wrong? The bug is before. Still right? It is after. Repeat.
  5. Change one thing at a time, and re-run.
  6. Explain it aloud (rubber-duck debugging) when stuck: describing the code line by line often reveals the wrong assumption.
  7. Add a test that fails without the fix, so the bug cannot come back (see Testing in Kotlin).
  8. Remove the debug prints or turn them into proper log statements.

Beyond println: debuggers and loggers

Printing has limits. You have to edit and rerun the program for every question, and a forgotten println can reach production. Two tools take over in real projects:

  • A debugger (IntelliJ IDEA, Android Studio) lets you set a breakpoint on a line, pause the program there, inspect every variable, step over or into calls, and evaluate expressions in the paused state. It is the right tool for complex state and for code you did not write. You can run a Kotlin program under the debugger just by clicking the gutter next to fun main().
  • A logging library (SLF4J with Logback or Log4j2 on the JVM, or the java.util.logging package in the JDK) writes messages with a level (TRACE, DEBUG, INFO, WARN, ERROR), a timestamp and a source, can be switched on and off by configuration, and can write to files or monitoring systems. Use it for anything that runs on a server. A typical call (read-only, as it needs a library):
Kotlin
// read-only example: SLF4J logging (needs the slf4j-api dependency)
import org.slf4j.LoggerFactory

private val log = LoggerFactory.getLogger("Orders")

fun placeOrder(id: Int) {
    log.info("placing order {}", id)
    try {
        // ...
    } catch (e: Exception) {
        log.error("order {} failed", id, e)    // the last argument is logged with its stack trace
    }
}

The {} placeholders avoid building the message when the level is disabled. Never write secrets, passwords or full credit-card numbers to logs.

Treat println as scaffolding. It is wonderful while you explore, but code that stays should either be silent or use a logger. Search for forgotten prints with your IDE before you commit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does println(intArrayOf(1, 2, 3)) print something like [I@5a07e868?

    Arrays inherit Any.toString, which prints a type code and hash. contentToString() and contentDeepToString() print the elements.
  2. 2. In a stack trace, where do you usually look first for your own code?

    The top at lines are the innermost calls. The first one in your own code shows where the exception was raised; lines below show who called it.
  3. 3. What does the dbg extension in this lesson return?

    dbg prints and returns this, so it can be inserted in the middle of a call chain without changing the result.
  4. 4. Which stream should debugging diagnostics usually go to, so they do not mix with a program's real output?

    stderr can be redirected separately from stdout, so a shell pipeline or file keeps results and diagnostics apart.
  5. 5. Which is NOT a good habit for toString and logging?

    Secrets end up in logs and consoles. Keep them out of toString and log messages.

Summary

  • Label what you print (println("total=$total")), put quotes around strings, and print at decision points.
  • A generic fun <T> T.dbg(label) extension lets you peek inside call chains; also does it for one-offs.
  • Give classes a readable toString (data classes get one); use contentToString() for arrays.
  • Diagnostics belong on stderr (System.err) or in a logger, not mixed with a program's results.
  • Read a stack trace from the top: exception and message, the first at line in your code, then the callers. Use stackTraceToString() and Throwable().stackTrace to get traces on demand.
  • Use require, check and error to make assumptions fail early with a clear message.
  • Graduate from println to a debugger and a logging library for larger programs, and remove debug prints before you commit.

Next: Regular Expressions