Kotlin addSuppressed()

Kotlin addSuppressed()

In Kotlin, the addSuppressed() method is used to add an exception to the suppressed exceptions list of another exception.

This method is typically used in conjunction with try-with-resources to manage resources and handle exceptions more effectively.

In this tutorial, we’ll explore the syntax of the addSuppressed() method and provide examples of its usage in Kotlin.


The syntax of the addSuppressed() method is:

fun addSuppressed(exception: Throwable): Unit

The addSuppressed() method adds the specified exception to the list of suppressed exceptions associated with the current exception.


1. Using addSuppressed() in Exception Handling

In this example, we’ll use addSuppressed() to add a suppressed exception when an exception occurs during resource management.

Kotlin Program

fun main() {
    val resource = CustomResource()

    try {
        // Code that may throw exceptions while using the resource
        throw CustomException("An error occurred during resource usage")
    } catch (e: Exception) {
        val suppressedException = AnotherException("Suppressed error")
    } finally {

class CustomResource {
    fun close() {
        // Code to release the resource
        println("Closing the resource...")

class CustomException(message: String) : Exception(message)
class AnotherException(message: String) : Exception(message)


CustomException: An error occurred during resource usage
	at MainKt.main(Main.kt:6)
	at MainKt.main(Main.kt)
	Suppressed: AnotherException: Suppressed error
		at MainKt.main(Main.kt:8)
		... 1 more
Closing the resource...

In this example, the addSuppressed() method is used to add a AnotherException to the suppressed exceptions list when an exception occurs within the try block.


In this tutorial, we’ve covered the addSuppressed() method in Kotlin, its syntax, and how to use it for managing suppressed exceptions during resource handling. This method is particularly useful in scenarios where multiple exceptions can occur, and you want to ensure that all exceptions are appropriately recorded.