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.

Syntax

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.

Example

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")
        e.addSuppressed(suppressedException)
        e.printStackTrace()
    } finally {
        resource.close()
    }
}

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)

Output

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.

Summary

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.