Stack traces

suggest change

A stack trace is a snapshot of active function call frames at the moment an exception was instantiated or a thread state was captured. Reading, formatting, and analyzing stack traces is essential for diagnosing bugs and crashes in Kotlin applications.


Anatomy of a Stack Trace

java.lang.IllegalArgumentException: Port number 99999 out of range
    at com.example.ServerConfig.validate(ServerConfig.kt:18)
    at com.example.ServerConfig.<init>(ServerConfig.kt:8)
    at com.example.ApplicationKt.startServer(Application.kt:42)
    at com.example.ApplicationKt.main(Application.kt:12)
  1. Exception Type: java.lang.IllegalArgumentException
  2. Error Message: Port number 99999 out of range
  3. Call Frames: Ordered from deepest (where the error occurred) to highest (the entry point like main). Each frame identifies:
    • Package and Class: com.example.ServerConfig
    • Method / Constructor: validate or <init>
    • Source file and line number: ServerConfig.kt:18

Capturing and Printing Stack Traces

Converting to String with stackTraceToString()

In standard Java, converting a stack trace to a string requires verbose StringWriter and PrintWriter wrappers. Kotlin provides the stackTraceToString() extension function directly on Throwable:

fun processOrder(orderId: String) {
    try {
        validateOrder(orderId)
    } catch (e: Exception) {
        // Convert the full stack trace into a standard Kotlin String
        val trace: String = e.stackTraceToString()
        
        // Log or send to crash reporting service
        println("Crash report:\n$trace")
    }
}

fun validateOrder(id: String) {
    require(id.isNotBlank()) { "Order ID cannot be blank" }
}

Inspecting StackTraceElement Programmatically

You can inspect individual frames using e.stackTrace, which returns an array of java.lang.StackTraceElement:

fun logRootFrame(e: Throwable) {
    val topFrame: StackTraceElement? = e.stackTrace.firstOrNull()
    if (topFrame != null) {
        println("Error occurred in ${topFrame.className}.${topFrame.methodName}() at line ${topFrame.lineNumber}")
    }
}

Inspecting Current Thread Execution

To capture the current call stack without throwing an exception:

fun printCurrentCallStack() {
    val stack = Thread.currentThread().stackTrace
    println("Current call hierarchy:")
    stack.drop(2).take(5).forEach { frame ->
        println(" -> ${frame.className}.${frame.methodName} (${frame.fileName}:${frame.lineNumber})")
    }
}

Coroutine Stack Traces (Suspension Recovery)

When an exception is thrown inside a coroutine, standard thread stack traces lose context across asynchronous suspension points (delay, network I/O, database calls).

Kotlin's coroutines library features stack trace recovery, which reconstructs the asynchronous invocation path when an exception crosses a coroutine boundary (withContext, async/await). It is active only in debug mode, which is on when assertions are enabled (-ea, the default when running tests or from the IDE) or with -Dkotlinx.coroutines.debug=on:

import kotlinx.coroutines.*

suspend fun fetchData(): String = withContext(Dispatchers.IO) {
    delay(50) // Suspension point
    throw IllegalStateException("Remote API offline")
}

suspend fun loadUserProfile() {
    delay(10)
    fetchData()
}

fun main() = runBlocking {
    try {
        loadUserProfile()
    } catch (e: Exception) {
        println(e.stackTraceToString())
    }
}

Output with -ea includes reconstructed coroutine frames, followed by the original exception as the cause:

java.lang.IllegalStateException: Remote API offline
	at ExampleKt$fetchData$2.invokeSuspend(Example.kt:5)
	at _COROUTINE._BOUNDARY._(CoroutineDebugging.kt:42)
	at ExampleKt.fetchData(Example.kt:3)
	at ExampleKt.loadUserProfile(Example.kt:10)
	at ExampleKt$main$1.invokeSuspend(Example.kt:15)
Caused by: java.lang.IllegalStateException: Remote API offline
	at ExampleKt$fetchData$2.invokeSuspend(Example.kt:5)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:34)
	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:100)
	...

Without debug mode only the frames of the thread that ran the failing code are shown: loadUserProfile and main are missing.

Enabling Debug Probes in Production or Tests

To enable coroutine debug mode (stack trace recovery and coroutine names in thread names) outside of tests, add the VM option:

-Dkotlinx.coroutines.debug=on

For coroutine dumps, install the debug probes from kotlinx-coroutines-debug, for example in unit tests:

import kotlinx.coroutines.debug.DebugProbes

fun setup() {
    DebugProbes.install()
    // Dump all active coroutines and their suspended traces
    DebugProbes.dumpCoroutines()
}

Logging Stack Traces with SLF4J and kotlin-logging

Always pass the Throwable instance as an argument to the logging framework rather than printing manually:

import io.github.oshai.kotlinlogging.KotlinLogging

private val logger = KotlinLogging.logger {}

fun executeTask() {
    try {
        riskyOperation()
    } catch (e: Exception) {
        // Correct: Passes exception to logger, preserving formatting and log metadata
        logger.error(e) { "Task execution failed for operation" }
    }
}

fun riskyOperation() {
    throw RuntimeException("Database timeout")
}

Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents